用的是广度优先搜索+位运算。
这是我AC的第一题,做了两天,纪念一下。
View Code
1 #include<iostream>
2
3 using namespace std;
4
5 unsigned short temp;
6 int top=0;
7 int rear=0;
8 unsigned short queue[65535];
9 int step[65535];
10 bool status[65535];
11
12
13 void init()
14 {
15 for(int i=0; i<4; i++)
16 for(int j=0; j<4; j++)
17 {
18 char c;
19 cin>>c;
20 if(c == 'b')
21 temp |= 1 << (4*i+j);
22 }
23 queue[top++]=temp;
24 status[temp]=true;
25 }
26
27
28 unsigned short flip(unsigned short beforeFlip, int i)
29 {
30 unsigned short afterFlip = beforeFlip;
31 afterFlip ^= 1<<i;
32 if((i%4)!=0) afterFlip ^= 1<<(i-1);
33 if((i+1)%4!=0) afterFlip ^= 1<<(i+1);
34 if(i>=4) afterFlip ^= 1<<(i-4);
35 if(i<=12) afterFlip ^= 1<<(i+4);
36 return afterFlip;
37 }
38
39
40 bool dfs()
41 {
42 int mid;
43 while(rear < top)
44 {
45 unsigned short curr = queue[rear++];
46 // cout<<"curr"<<curr<<endl;
47 if(curr == 0 ||curr == 65535)
48 {
49 cout<<step[curr];
50 return true;
51
52 }
53 for(int i=0;i<=15;i++)
54 {
55 unsigned short curr2 = flip(curr,i);
56 if(!status[curr2])
57 {
58 queue[top++]=curr2;
59 status[curr2]=true;
60 step[curr2]=step[curr]+1;
61 }
62 }
63
64 // cout<<"step"<<step<<endl;
65 }
66 return false;
67 }
68
69
70 int main()
71 {
72 init();
73 if(!dfs())
74 cout<<"Impossible";
75 }