poj 2488 A Knight's Journey

首先要清楚棋盘行列表示方法。

注意要求按字典序输出,我的搜索方向是 dx[ ],dy[ ].

dfs初步,具体看代码。

 1 #include <iostream>
 2 #include<stdio.h>
 3 #include<cstring>
 4 using namespace std;
 5 int visit[10][10];
 6 
 7 struct Step
 8 {
 9     int x,y;
10 };
11 Step step[100];
12 int p,q;  //p是行(数字),q是列(字母)
13 int dx[8]={-1,1,-2,2,-2,2,-1,1};  //要满足字典序,顺序不能改
14 int dy[8]={-2,-2,-1,-1,1,1,2,2};
15 bool dfs(int i,int j,int no)
16 {
17       visit[i][j] = 1;
18       step[no].x = i;
19       step[no].y = j;
20       if(no == p*q)
21        return true;
22     for(int k =0;k < 8;k++)
23     {
24         int xx = i + dx[k];
25         int yy = j + dy[k];
26         if(xx > 0 && xx <= p && yy > 0 && yy <=q && !visit[xx][yy])
27             if(dfs(xx,yy,no+1)) return true;  //如果满足就跳出递归
28     }
29           visit[i][j] = 0;  //如果到了这一步,说明没有满足情况的
30           return false;    //此步骤记录归0,返回上一步
31 }
32 
33 int main()
34 {
35    int n;
36    scanf("%d",&n);
37    int count = 1;
38    while(n--)
39    {
40 
41        bool ans = false;
42        memset(visit,0,sizeof(visit));
43        scanf("%d %d",&p,&q);
44        for(int j = 1;j <= q;j++)
45        {
46            for(int i = 1;i <= p;i++)
47            {
48                int no = 1; //no表示第几步
49                ans = dfs(i,j,no);
50                if(ans)
51                    break;
52            }
53            if(ans)
54               break;
55        }
56            printf("Scenario #%d:\n",count++);
57            if(ans)
58            {
59                for(int i =1;i <= p*q;i++)
60                    printf("%c%d",step[i].y + 'A' - 1,step[i].x);
61                    printf("\n");
62            }
63            else
64            printf("impossible\n");
65            printf("\n");
66    }
67     return 0;
68 }

 

posted @ 2013-10-03 17:44  小の泽  阅读(118)  评论(0编辑  收藏  举报