3530 - C.拼盘游戏(已更正输入答案)
时间限制 : 1 秒
内存限制 : 128 MB
数字拼盘拼盘游戏是一个有趣的智力游戏,在窗体上有9个方格,分别有0-8共9个数字(如下所示),其中0是可以和相邻数字互换,其中U、D、L和R分别表示0和上下左右相邻的数字互换,如下所示是0和下面相邻的数字互换的后的结果。求0经过一系列互换后,输出最后的窗体数字。
3 4 0 3 4 5
7 8 5 à 7 8 0
6 1 2 6 1 2
<br />
题目输入
输入9个数字,表示窗体的初始状态,然后输入一些列字母 (U、D、L或R),输入E表示字母输入结束。
题目输出
输出最后的窗体数字,每个数字之间有空格
输入/输出样例
输入格式
3 4 0 7 8 5 6 1 2 D D L U L R R E
输出格式
3 4 5 7 2 0 6 8 1
C语言解答
#include <stdio.h> int main() { int arr[3][3]; int i, j, temp; int zero[2]; char c; for(i = 0; i < 3; i++) { for(j = 0; j < 3; j++) { scanf("%d", &arr[i][j]); if(arr[i][j] == 0) { zero[0] = i; zero[1] = j; } } } i = zero[0]; j = zero[1]; scanf("%c", &c); while(c != 'E') { switch(c) { case 'U': i--; break; case 'D': i++; break; case 'L': j--; break; case 'R': j++; break; } temp = arr[i][j]; arr[i][j] = 0; arr[zero[0]][zero[1]] = temp; zero[0] = i; zero[1] = j; scanf("%c", &c); } for(i = 0; i < 3; i++) { printf("%d %d %d\n", arr[i][0], arr[i][1], arr[i][2]); } return 0; }
C++解答
#include<iostream> #include<string> using namespace std; void swap(int *a,int *b){ int *t =a; a = b; b = t; } int main(){ int xi,xj,x; int a[3][3]; for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ cin>>x; a[i][j] = x; if(x==0){ xi=i; xj=j; } } } char ch; // while(cin>>ch && *ch!='E') // cout<<ch; while(cin>>ch&&ch!='E'){ if(ch=='U'){ swap(a[xi][xj],a[xi-1][xj]); xi = xi-1; } else if(ch=='D'){ swap(a[xi][xj],a[xi+1][xj]); xi = xi+1; } else if(ch=='L'){ swap(a[xi][xj],a[xi][xj-1]); xj = xj-1; } else if(ch=='R'){ swap(a[xi][xj],a[xi][xj+1]); xj = xj+1; } } for(int m=0;m<3;m++){ for(int n=0;n<3;n++){ if(n==0) cout<<a[m][n]; else cout<<" "<<a[m][n]; } cout<<endl; } return 0; } /* 3 4 0 7 8 5 6 1 2 D D L U L R R E */
Java解答
import java.util.Scanner; public class Main { public static int[] a = new int[9]; public static void main(String[] args) { int t = 0, n, i; String s; Scanner in = new Scanner(System.in); for (i = 0; i < 9; i++) { n = in.nextInt(); if (n == 0) { t = i; } a[i] = n; } while (in.hasNext()) { s = in.next(); if (s.equals("U")) { s(t, t - 3); t = t - 3; } if (s.equals("D")) { s(t, t + 3); t = t + 3; } if (s.equals("L")) { s(t, t - 1); t = t - 1; } if (s.equals("R")) { s(t, t + 1); t = t + 1; } if (s.equals("E")) { break; } } for (i = 0; i < 9; i++) { if ((i + 1) % 3 != 0) { System.out.print(a[i] + " "); } else { System.out.println(a[i]); } } } public static void s(int x, int y) { int t = a[x]; a[x] = a[y]; a[y] = t; } }