1.题目描述:点击打开链接
2.解题思路:本题是一道模拟题,只需要根据题意的四种命令模拟这些过程即可。不过在字符串处理上要小心。由于本题把‘Z‘当做结束标志,因此可以认为网格中不存在字符’Z‘。为了提高效率,不必提前存好所有的命令,只需要一个个读即可。如果遇到非法命令,令判断标志ok=0,后续的命令直接忽略即可。
3.代码:
#define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<algorithm> #include<string> #include<sstream> #include<set> #include<vector> #include<stack> #include<map> #include<queue> #include<deque> #include<cstdlib> #include<cstdio> #include<cstring> #include<cmath> #include<ctime> #include<functional> using namespace std; #define N 10 char g[N][N]; char*cmd = "ABLR"; int x, y; bool swap(char c) { switch (c) { case 'A': if (x-1>=0){ swap(g[x - 1][y], g[x][y]); x--; } else return false; break; case 'B': if (x+1<=4){ swap(g[x + 1][y], g[x][y]); x++; } else return false; break; case 'L': if (y-1>=0){ swap(g[x][y - 1], g[x][y]); y--; } else return false; break; case 'R': if (y+1<=4){ swap(g[x][y + 1], g[x][y]); y++; } else return false; break; } return true; } void print_ans() { for (int i = 0; i < 5; i++) for (int j = 0; j < 5; j++) printf("%c%c", g[i][j], j == 4 ? '\n' : ' '); } int main() { //freopen("t.txt", "r", stdin); int rnd = 0; char c; while (1) { memset(g, '\0', sizeof(g)); if (rnd)getchar(); for (int i = 0; i < 5; i++) { fgets(g[i], sizeof(g[i]), stdin); g[i][5] = '\0'; } for (int i = 0; i < 5;i++) for (int j = 0; j < 5;j++) if (g[i][j] == ' ') { x = i; y = j; } else if (g[i][j] == 'Z')return 0; int ok = 1; while ((c = getchar()) != '0') { if (!ok)continue;//后续命令直接忽略 if (strchr(cmd, c) != NULL){ if (!swap(c))ok = 0; } } if (rnd)cout << endl; printf("Puzzle #%d:\n", ++rnd); if (!ok)printf("This puzzle has no final configuration.\n"); else print_ans(); } return 0; }
原文:http://blog.csdn.net/u014800748/article/details/44543311