ZOJ 2416题解BFS

 1 思路:此题属于隐式图的搜索,从1111出发发散成一个
2 树状结构从每一层中搜索看是否由于目标相等的数,有责打
3 印无责要还原;先对每个数加1,再减1,最后左右互换;
4 #include<cstdio>
5 #include<cstring>
6 #include<iostream>
7 #include<cstdlib>
8 #include<queue>
9
10 using namespace std;
11
12 typedef struct
13 {
14 int data;
15 int step;
16 }State;//结构体存放步长和数据;
17
18 int Equal(State s1, State s2)//判断两个数相等
19 {
20 if(s1.data == s2.data)
21 return 1;
22 return 0;
23 }
24 int visit[10000], a[5], b[5];
25 queue<State>q;
26 int main()
27 {
28 int i, ncases;
29 State start, end;
30 scanf("%d", &ncases);
31
32 while( ncases-- )
33 {
34 memset(visit, 0, sizeof(visit));
35 scanf("%d %d", &start.data, &end.data);
36 visit[start.data] = 1;
37 start.step = 0;
38 q.push(start);
39 while( !q.empty() )
40 {
41 State u = q.front();
42 q.pop();
43 if( Equal(u, end) )
44 {
45 printf("%d\n", u.step);
46 break;
47 }
48 for(i=0; i<4; i++)
49 {
50 b[i] = a[i] = u.data % 10;
51 u.data = u.data/10;
52 }
53 for(i=0; i<4; i++)
54 {
55 State v = u;
56 v.step = u.step + 1;
57 b[i] = a[i]%9 + 1;
58 v.data = b[3]*1000 + b[2]*100 + b[1]*10 + b[0];
59 if( !visit[v.data] )
60 {
61 q.push(v);
62 visit[v.data] = 1;
63 }
64 b[i] = a[i];//还原
65 b[i]--;
66 if(b[i] == 0)
67 b[i] = 9;
68 v.data = b[3]*1000 + b[2]*100 + b[1]*10 + b[0];
69 if( !visit[v.data] )
70 {
71 q.push(v);
72 visit[v.data] = 1;
73 }
74 b[i] = a[i];
75 }
76 for(i=0; i<3; i++)
77 {
78 b[i] = a[i+1];
79 b[i+1] = a[i];
80 State v = u;
81 v.step = u.step + 1;
82 v.data = b[3]*1000 + b[2]*100 + b[1]*10 + b[0];
83 if( !visit[v.data] )
84 {
85 q.push(v);
86 visit[v.data] = 1;
87 }
88 b[i] = a[i];
89 b[i+1] = a[i+1];
90 }
91 }
92 while( !q.empty() )
93 {
94 q.pop();
95 }
96 }
97 return 0;
98 }
posted @ 2012-02-26 11:49  zhongya  阅读(240)  评论(0编辑  收藏  举报