给一个矩形棋盘,每次走日字,问能否不重复的走完棋盘的每个点,并将路径按字典序输出
*解法:按字典序输出路径,因此方向向量的数组按字典序写顺序,dfs+回溯,注意flag退出递归的判断,并且用pre记录路径
#include <iostream> #include <cstdio> #include <cstring> using namespace std; char a[30][30]; int dx[] = {-2, -2, -1, -1, 1, 1, 2, 2}; int dy[] = {-1, 1, -2, 2, -2, 2, -1, 1}; int vis[30][30]; int P, Q, flag = 0; struct node { int x, y; }pre[30][30]; void dfs(int x, int y, int step) { if(step == P * Q) { flag = 1; return; } if(flag) return;//全走完了之后就不用再走了 for(int i = 0; i < 8; i++) { int xx = x + dx[i], yy = y + dy[i]; if(xx >= 0 && xx < P && yy >= 0 && yy < Q && !vis[xx][yy]) { vis[xx][yy] = 1; step++; pre[x][y] = (node){xx, yy};//用pre输出路径 dfs(xx, yy, step); if(flag) return;//===全走完了之后就不用再走了=== vis[xx][yy] = 0; step--; } } return; } int main() { int T, cc = 0; scanf("%d", &T); while(T--) { scanf("%d %d", &Q, &P); memset(vis, 0, sizeof(vis)); flag = 0; vis[0][0] = 1; dfs(0,0,1); printf("Scenario #%d:\n", ++cc); if(!flag) printf("impossible\n"); else { int ux = 0, uy = 0, vx, vy; for(int i = 0; i < P * Q; i++) { char c = ux + ‘A‘; int z = uy + 1; printf("%c%d", c, z); vx = pre[ux][uy].x, vy = pre[ux][uy].y; ux = vx, uy = vy; } printf("\n"); } printf("\n"); } return 0; }