有时候题解要写的简略一点...于是:

裸的bfs妥妥的。。。

注意hash函数的选取及判断重复即可

结果memcpy函数写错了,调了好长好长时间、、、哭T T...

(据说不判重也可以过。。。汗!)

 

 1 /**************************************************************
 2     Problem: 1054
 3     User: rausen
 4     Language: C++
 5     Result: Accepted
 6     Time:28 ms
 7     Memory:3060 kb
 8 ****************************************************************/
 9  
10 #include <cstdio>
11 #include <cstring>
12 #include <algorithm>
13   
14 using namespace std;
15 const int dx[4] = {0, 0, 1, -1};
16 const int dy[4] = {1, -1, 0, 0};
17 bool Ans[5][5], vis[70000];
18 struct data{
19     bool a[5][5];
20     int step;
21 }q[70000];
22 int begin, end, H;
23 int l, r;
24   
25 int hash(bool a[5][5]){
26     int k = 1, res = 0, i, j;
27     for (i = 1; i <= 4; ++i)
28         for (j = 1; j <= 4; ++j)
29             res += k * a[i][j], k <<= 1;
30     return res;
31 }
32   
33 int main(){
34     char ch[5];
35     int i, j, k, X, Y;
36     for (i = 1; i <= 4; ++i)
37         for (j = 1, scanf("%s", ch); j <= 4; ++j)
38             q[0].a[i][j] = ch[j - 1] - '0';
39     for (i = 1; i <= 4; ++i)     
40         for (j = 1, scanf("%s", ch); j <= 4; ++j)
41             Ans[i][j] = ch[j - 1] - '0';
42     begin = hash(q[0].a);
43     end = hash(Ans);
44     if (begin == end){
45         printf("0\n");
46         return 0;
47     }
48     vis[begin] = 1;
49     for (l = r = 0; l <= r; ++l)
50         for (i = 1; i <= 4; ++i)
51             for (j = 1; j <= 4; ++j)
52                 if (q[l].a[i][j]) for (k = 0; k < 4; ++k){
53                     X = i + dx[k], Y = j + dy[k];
54                     if (X < 1 || Y < 1 || X > 4 || Y > 4 || q[l].a[X][Y])
55                         continue;
56                     swap(q[l].a[i][j], q[l].a[X][Y]);
57                     H = hash(q[l].a);
58                     if (!vis[H]){
59                         if (H == end){
60                             printf("%d\n", q[l].step + 1);
61                             return 0;
62                         }
63                         vis[H] = 1;
64                         q[++r].step = q[l].step + 1;    
65                         memcpy(q[r].a, q[l].a, sizeof(q[r].a));
66                     }
67                     swap(q[l].a[i][j], q[l].a[X][Y]);
68                 }
69     return 0;
70 }
View Code

 

posted on 2014-10-30 15:35  Xs酱~  阅读(234)  评论(0编辑  收藏  举报