poj 2488 A Knight's Journey

http://poj.org/problem?id=2488  【DFS 】  一个p*q的棋盘,从一个点开始,骑士每次漫游都会在一个方向移动两个格子,并在垂直的方向移动一个格子。问题是,有没有这样一种漫游方法,每次骑士经过的地方都不同并且能够遍历整个棋盘?.要求 lexicographically first path,就是字典需最靠前的路径,这个就需要选择两个探测增量的时候考虑一下。先优先x后优先y,所以
int dx[]={-2,-2,-1,-1,1,1,2,2};
int dy[]={-1,1,-2,2,-2,2,-1,1};//保证路径按字典序,搜索时应自左向右,自上而下

View Code
 1 #include<iostream>
2 #include<vector>
3 #include<cstring>
4 using namespace std;
5 struct node
6 {
7 int x,y;//路径
8 public: node(int a,int b):x(a),y(b){}
9 };
10 vector<node>path;
11 bool mat[30][30];
12 int dx[8]={ -1, 1, -2, 2, -2, 2, -1, 1};
13 int dy[8]={ -2,-2, -1,-1, 1, 1, 2, 2};//搜索时,按照字典序
14 int row,col;
15 bool flag;
16 void init()
17 {
18 path.clear();
19 memset(mat,false,sizeof(mat));
20 flag=false;
21 }
22 void dfs(int x,int y,int step)//深度遍历
23 {
24 if(!flag)//
25 {
26 mat[x][y]=true;//走过 ,
27 path.push_back(node(x,y));
28 if(step==row*col || flag)
29 {
30 flag=true;
31 return;
32 }
33 else
34 {
35 for(int i=0;i<8;i++)
36 {
37 int r=x+dx[i];
38 int c=y+dy[i];
39 if(r>-1 && c>-1 && r<row && c<col &&!mat[r][c])
40 {
41 dfs(r,c,step+1);
42 mat[r][c]=false;
43 if(!flag) path.pop_back();//if flag==true path里面是完整路径,不用动了
44 }
45 }
46 }
47 }
48 }
49 int main()
50 {
51 int t,num=0;
52 cin>>t;
53 while(t--)
54 {
55 cin>>row>>col;
56 init();
57 dfs(0,0,1);
58 cout<<"Scenario #"<<++num<<":"<<endl;
59 if(flag)
60 {
61 int i;
62 for(i=0;i<path.size()-1;i++) cout<<char(path[i].y+'A')<<path[i].x+1;
63 cout<<char(path[i].y+'A')<<path[i].x+1<<endl;
64 }
65 else cout<<"impossible"<<endl;
66 cout<<endl;
67 }
68 return 0;
69 }


 

posted @ 2012-04-05 18:08  keepmoving89  阅读(166)  评论(0编辑  收藏  举报