题目链接:http://acm.timus.ru/problem.aspx?space=1&num=1298
1298. Knight
Time limit: 2.0 second
Memory limit: 64 MB Even paratroopers have vacations. The flight to Sirius in the depths of “The Admiral Brisco” Leo Hao whiled away with chessboard. No, he did not like usual chess game, and in addition, he did not have
likely rival. The whole day Leo amused himself with an interesting thing: he tried to travel over all cells of the chessboard with the knight so that the knight visited each cell only one time. Leo attempted one time, then second, but always something was
wrong. Leo became a little angry. Then he attempted board 4*4 instead of 8*8. Again failure after failure. A little angry, with the chessboard under his arm, Leo went to look for a local programmer. They two together indeed will solve this problem.
InputThere is only one number N (1 ≤ N ≤ 8) in the input.
OutputIf it is possible to travel with the knight over the square field N×N cells, then output should contain N2 lines
with tour over the chessboard with mentioned property, otherwise the only word “IMPOSSIBLE”.
Samples
|
输出能跳完所有格子的路径!
代码如下:
#include <cstdio> #include <cstring> int xx[8]= {2,1,-1,-2,-2,-1,1,2}; int yy[8]= {1,2,2,1,-1,-2,-2,-1}; int vis[17][17]; int n; int judge(int x, int y) { if((x>=1&&x<=n) && (y>=1&&y<=n) && !vis[x][y]) return 1; return 0; } int dfs(int x, int y, int num) { if(num == n*n) return 1; for(int i = 0; i < 8; i++) { int dx = x+xx[i]; int dy = y+yy[i]; if(judge(dx,dy)) { vis[dx][dy] = num+1; if(dfs(dx,dy,num+1)) { return 1; } vis[dx][dy] = 0; } } return 0; } int main() { while(~scanf("%d",&n)) { memset(vis,0,sizeof(vis)); vis[1][1] = 1; if(n == 1) { printf("a1\n"); continue; } if(n==2 || n==3 || n==4) { printf("IMPOSSIBLE\n"); continue; } int flag = 0; flag = dfs(1,1,1); if(!flag) { printf("IMPOSSIBLE\n"); } else { for(int k = 1; k <= n*n; k++) { for(int i = 1; i <= n; i++) { for(int j = 1; j <= n; j++) { if(vis[i][j] == k) { printf("%c%d\n",i+'a'-1,j); } } } } } } return 0; }
原文地址:http://blog.csdn.net/u012860063/article/details/44119087