广度优先搜索+位运算+递归输出路径。
这道题关键是输出路径是很难的,其中参考了网上的一种递归输出的方法,需留意。
View Code
1 #include<iostream>
2 using namespace std;
3
4 unsigned short handles;
5 unsigned short queue[65535];
6 int father[65535];
7 int cx[65535],cy[65535];
8 bool flag[65535];
9 unsigned short door[16]={0x111f,0x222f,0x444f,0x888f,0x11f1,0x22f2,0x44f4,0x88f8,0x1f11,0x2f22,0x4f44,0x8f88,0xf111,0xf222,0xf444,0xf888};
10
11 int rear=0,top=0;
12
13 void outprint(int x,int y)
14 {
15 if(father[x]==-1)
16 {
17 cout<<y<<endl;
18 return;
19 }
20 outprint(father[x],y+1);
21 cout<<cx[x]<<" "<<cy[x]<<endl;
22 }
23
24 void init()
25 {
26 for(int i=0;i<4;i++)
27 for(int j=0;j<4;j++)
28 {
29 char c;
30 cin>>c;
31 if('+'==c)
32 handles|=1<<(4*i+j);
33 }
34 flag[handles]=true;
35 queue[top++]=handles;
36 father[top-1]=-1;
37 }
38
39 unsigned short change(unsigned short state,int i)
40 {
41 unsigned short temp=state;
42 temp ^= door[i];
43 return temp;
44 }
45
46 void dfs()
47 {
48 while(rear<top)
49 {
50 for(int i=0;i<=15;i++)
51 {
52 unsigned short nowstate = change(queue[rear],i);
53 if(!flag[nowstate])
54 {
55 queue[top++]=nowstate;
56 flag[nowstate]=true;
57 father[top-1]=rear;
58 cx[top-1]=i/4+1;
59 cy[top-1]=i%4+1;
60 }
61 if(nowstate==0)
62 {
63 outprint(top-1,0);
64 return;
65 }
66 }
67 rear++;
68 }
69 }
70
71 int main()
72 {
73 init();
74 dfs();
75 return 0;
76
77 }
晚上连夜回家搬电脑,
继续加油!