poj 2488 DFS

水题,注意字典序输出

 1 #include <iostream>
2 #include <stdio.h>
3 #include <string.h>
4 using namespace std;
5 const int maxx=50;
6 int dir[8][2]={{-2,-1},{-2,1},{-1,-2},{-1,2},{1,-2},{1,2},{2,-1},{2,1}};
7 int n,m,p1[maxx*maxx+2],p2[maxx*maxx+2],cnt;
8 bool visit[maxx+2][maxx+2];
9
10 bool judge(int a,int b)
11 {
12 if(a>=1 && a<=n && b>=1 && b<=m)
13 return 1;
14 return 0;
15 }
16
17 void dfs(int x,int y,int val)
18 {
19 int i,j,a,b;
20 for(i=0;i<=7;i++)
21 {
22 a=x+dir[i][0];
23 b=y+dir[i][1];
24 if(judge(a,b) && !visit[a][b])
25 {
26 //cout<<x<<" "<<y<<"**"<<cnt<<"**" <<" "<<a<<" "<<b<<endl;
27 visit[a][b]=1;
28 cnt=val;
29 p1[cnt]=a;
30 p2[cnt]=b;
31 dfs(a,b,++cnt);
32 if(cnt==n*m) return ;
33 visit[a][b]=0;
34 }
35 }
36 }
37
38 int main()
39 {
40 int t,tt,i;
41 //freopen("in.txt","r",stdin);
42 scanf("%d",&t);
43 for(tt=1;tt<=t;tt++)
44 {
45 scanf("%d%d",&m,&n);
46 cnt=1;
47 memset(visit,0,sizeof(visit));
48 visit[1][1]=1;
49 dfs(1,1,1);
50 printf("Scenario #%d:\n",tt);
51 if(cnt==n*m)
52 {
53 printf("A1");
54 for(i=1;i<cnt;i++)
55 printf("%c%d",p1[i]+'A'-1,p2[i]);
56 }
57 else
58 printf("impossible");
59 printf("\n");
60
61 printf("\n");
62 }
63 return 0;
64 }



原文地址:https://www.cnblogs.com/inpeace7/p/2423448.html