平台:
UVa Online Judge
題號:
227 - Puzzle
題目連結:
q
題目說明:
有一个5*5的网格,其中恰好有一个格子是空的,其他格子各有一个字母。一共有4种指令:A, B, L, R,分别表示把空格上、下、左、右的相邻字母移到空格中。输入初始网格和指令序列(以数字0结束),输出指令执行完毕后的网格。如果有非法指令,应输出“Thispuzzle has no final configuration.”,例如,图3-5中执行ARRBBL0后,效果如图3-6所示。
範例輸入:
TRGSJ
XDOKI
M VLN
WPABE
UQHCF
ARRBBL0
ABCDE
FGHIJ
KLMNO
PQRS
TUVWX
AAA
LLLL0
ABCDE
FGHIJ
KLMNO
PQRS
TUVWX
AAAAABBRRRLL0
Z
範例輸出:
Puzzle #1:
T R G S J
X O K L I
M D V B N
W P A E
U Q H C F
Puzzle #2:
A B C D
F G H I E
K L M N J
P Q R S O
T U V W X
Puzzle #3:
This puzzle has no final configuration.
解題方法:
移动,其实也就是空格与周围的进行互换。可以用一个函数调用。处理输入的时候要注意回车的影响。
程式碼:
1 #include2 #include 3 //#define LOCAL 4 5 const int MAXN = 10; 6 const int N = 5; 7 8 char square[MAXN][MAXN] = { }; 9 char move[1024] = {}; 10 const char* msg = "This puzzle has no final configuration.\n"; 11 int cnt = 0; 12 13 bool moveP(char p, int& x, int& y) { 14 int i = x, j = y; 15 switch (p) { 16 case 'A': 17 x--; 18 break; 19 case 'B': 20 x++; 21 break; 22 case 'R': 23 y++; 24 break; 25 case 'L': 26 y--; 27 break; 28 default: 29 return false; 30 } 31 if (x < 0 || x == 5 || 32 y < 0 || y == 5) { 33 return false; 34 } 35 else { 36 square[i][j] = square[x][y] ; 37 square[x][y] = ' '; 38 } 39 return true; 40 } 41 42 //传入第一个字符 43 void scanSquare(char c, int* x, int* y) { 44 memset(square, 0, sizeof(square)); 45 square[0][0] = c; 46 char ch = ' '; 47 int j = 1; 48 for (int i = 0; i < N; i++) { 49 //这里已经隐形消去最后一个回车的影响 50 while ((ch = getchar()) != '\n') { 51 if (j < N) { 52 square[i][j++] = ch; 53 //记录空格位置 54 //如果一行中最后一个是空格就不会记录 55 if (ch == ' ') { 56 *x = i; 57 *y = j - 1; 58 } 59 } 60 else { 61 continue; 62 } 63 } 64 //弥补最后一个是空格 65 if (j == 4) { 66 *x = i; 67 *y = j; 68 } 69 j = 0; 70 } 71 } 72 73 void printSquare(bool flag) { 74 if (cnt) { 75 putchar('\n'); 76 } 77 printf("Puzzle #%d:\n", ++cnt); 78 if (flag) { 79 for (int i = 0; i < N; i++) { 80 for (int j = 0; j < N; j++) { 81 if (j) { 82 putchar(' '); 83 } 84 putchar(square[i][j]); 85 } 86 putchar('\n'); 87 } 88 } 89 else { 90 printf("%s", msg); 91 } 92 } 93 94 95 void scanMove() { 96 memset(move, 0, sizeof(move)); 97 char p = ' '; 98 int i = 0; 99 while ((p = getchar()) != '0') { 100 if (p == '\n') { 101 continue; 102 } 103 move[i++] = p; 104 } 105 //要消去最后的回车 106 getchar(); 107 } 108 109 int main() { 110 #ifdef LOCAL 111 freopen("in.txt", "r", stdin); 112 freopen("out.txt", "w", stdout); 113 #endif // LOCAL 114 115 char c = ' '; 116 //while (1) { 117 while ((c = getchar()) != 'Z') { 118 int x = 0, y = 0; 119 scanSquare(c, &x, &y); 120 //printf("\nzuobiao %d, %d \n\n", x, y); 121 bool flag = true; 122 scanMove(); 123 124 for (int i = 0; i < strlen(move); i++) { 125 flag = moveP(move[i], x, y); 126 if (!flag) { 127 break; 128 } 129 } 130 printSquare(flag); 131 //printf("MOVE = %s\n", move); 132 } 133 return 0; 134 }