poj 2488 A Knight's Journey

走马步,求能否遍历棋盘上所有格,如能,按最小字典序输出路径。

做这题时我又看了下以前写的poj 2676,把代码又改进了下。

 1 #include <stdio.h>
 2 #include <string.h>
 3 int X[] = {-2,-2,-1,-1,1,1,2,2},
 4     Y[] = {-1,1,-2,2,-2,2,-1,1};
 5 int m,n,path[26][2];
 6 bool find,vis[13][13];
 7 void dfs(int a,int b,int k)
 8 {
 9     int i,x,y;
10     //if(find) return ;
11     if(k >= m*n)
12     {
13         find = 1;
14         for(i = 0; i < m*n; i++)
15             printf("%c%d",path[i][0]+'A',path[i][1]+1);
16         printf("\n\n");
17         memset(vis,0,sizeof vis);
18         return;
19     }
20     for(i = 0; i < 8; i++)
21     {
22         x = a+X[i];
23         y = b+Y[i];
24         if(!find && x>=0 && y>=0 && x<m && y<n && !vis[x][y])
25         {
26             vis[x][y] = 1;
27             path[k][0] = x;
28             path[k][1] = y;
29             dfs(x,y,k+1);
30             vis[x][y] = 0;
31         }
32     }
33 }
34 int main()
35 {
36     int T,ca=1;
37     scanf("%d",&T);
38     while(T--)
39     {
40         scanf("%d%d",&n,&m);
41         printf("Scenario #%d:\n",ca++);
42         find = 0;
43         vis[0][0] = 1;
44         dfs(0,0,1);
45         if(!find) printf("impossible\n\n");
46     }
47     return 0;
48 }
原文地址:https://www.cnblogs.com/lzxskjo/p/2761698.html