poj 2965 BFS

状态压缩,记录路径

  1 #include <iostream>
2 #include <string.h>
3 #include <stdio.h>
4 using namespace std;
5 const int maxx=100000;
6 char c[4][4];
7 int que[maxx],cnt,step[maxx],n;
8 struct FF
9 {
10 int fa;
11 int path;
12 };
13 FF father[maxx];
14 int t[16]={63624,62532,61986,61713,36744,20292,
15 12066,7953,35064,17652,8946,4593,34959,17487,8751,4383};
16 bool visit[maxx];
17 void print(int x)
18 {
19 switch(x)
20 {
21 case 63624:printf("1 1\n");break;
22 case 62532:printf("1 2\n");break;
23 case 61986:printf("1 3\n");break;
24 case 61713:printf("1 4\n");break;
25 case 36744:printf("2 1\n");break;
26 case 20292:printf("2 2\n");break;
27 case 12066:printf("2 3\n");break;
28 case 7953:printf("2 4\n");break;
29 case 35064:printf("3 1\n");break;
30 case 17652:printf("3 2\n");break;
31 case 8946:printf("3 3\n");break;
32 case 4593:printf("3 4\n");break;
33 case 34959:printf("4 1\n");break;
34 case 17487:printf("4 2\n");break;
35 case 8751:printf("4 3\n");break;
36 case 4383:printf("4 4\n");break;
37 }
38 }
39 void bfs(int s)
40 {
41 int f,r,qfront,now;
42 f=0;
43 r=1;
44 visit[s]=1;
45 que[0]=s;
46 father[s].fa=0;
47 father[s].path=0;
48 while(f<r)
49 {
50 qfront=que[f];
51 f++;
52 for(int i=0;i<=15;i++)
53 {
54 now=qfront^t[i];
55 if(now==0)
56 {
57 father[now].fa=qfront;
58 father[now].path=i;
59 n=now;
60 step[now]=step[qfront]+1;
61 return ;
62 }
63 if(!visit[now])
64 {
65 father[now].fa=qfront;
66 father[now].path=i;
67 step[now]=step[qfront]+1;
68 visit[now]=1;
69 que[r]=now;
70 r++;
71 }
72 }
73 }
74 }
75
76 void dfs(int x)
77 {
78 if(father[x].fa==0)
79 return;
80 dfs(father[x].fa);
81 print(t[father[x].path]);
82 }
83
84 int main()
85 {
86 int s=0,i,j;
87 //freopen("iin.txt","r",stdin);
88 for(i=0;i<4;i++)
89 for(j=0;j<4;j++)
90 cin>>c[i][j];
91 for(i=0;i<4;i++)
92 for(j=0;j<4;j++)
93 {
94 if(c[i][j]=='+')
95 s=s^(1<<(15-4*i-j));
96 }
97 bfs(s);
98 printf("%d\n",step[0]);
99 dfs(n);
100 return 0;
101 }



posted on 2012-03-30 15:37  Inpeace7  阅读(152)  评论(0编辑  收藏  举报

导航