标签:
Description
Input
Output
Sample Input
bwwb bbwb bwwb bwww
Sample Output
4
题目大意:在一个4x4的棋盘上,摆满了黑白两种颜色的棋子。当翻转一颗棋子的时候,与它相邻的上下左右四个棋子也随之翻转。问将整个棋盘置为同一种颜色最少需要翻转几次。
题目分析:这道题的数据量不大且固定不变,2^16个状态,又因为让找最小步骤数,所以就敲定用BFS。接下来就是状态如何表示了,很显然了,4行用四个不超过16的二进制数表示即可。至于状态转移,用位运算异或就能轻松完成。
代码如下:
1 # include<iostream> 2 # include<cstdio> 3 # include<queue> 4 # include<cstring> 5 # include<algorithm> 6 using namespace std; 7 struct node 8 { 9 int a,b,c,d,t; 10 node(){} 11 node(int a1,int b1,int c1,int d1,int t1):a(a1),b(b1),c(c1),d(d1),t(t1){} 12 bool operator < (const node &a) const { 13 return t>a.t; 14 } 15 }; 16 char p[8][8]; 17 int vis [16][16][16][16]; 18 void bfs() 19 { 20 int temp[4],a,b,c,d; 21 for(int i=0;i<4;++i){ 22 temp[i]=0; 23 for(int j=0;j<4;++j){ 24 if(p[i][j]==‘b‘) 25 temp[i]=temp[i]*2+1; 26 else 27 temp[i]=temp[i]*2+0; 28 } 29 } 30 priority_queue<node>q; 31 memset(vis,0,sizeof(vis)); 32 vis[temp[0]][temp[1]][temp[2]][temp[3]]=1; 33 q.push(node(temp[0],temp[1],temp[2],temp[3],0)); 34 while(!q.empty()){ 35 node u=q.top(); 36 q.pop(); 37 if(u.a==15&&u.b==15&&u.c==15&&u.d==15){ 38 printf("%d\n",u.t); 39 return ; 40 } 41 if(!u.a&&!u.b&&!u.c&&!u.d){ 42 printf("%d\n",u.t); 43 return ; 44 } 45 for(int i=0;i<4;++i){ 46 a=u.a,b=u.b,c=u.c,d=u.d; 47 a^=(1<<i); 48 b^=(1<<i); 49 if(i>0) 50 a^=(1<<(i-1)); 51 if(i<3) 52 a^=(1<<(i+1)); 53 if(!vis[a][b][c][d]){ 54 vis[a][b][c][d]=1; 55 q.push(node(a,b,c,d,u.t+1)); 56 } 57 } 58 for(int i=0;i<4;++i){ 59 a=u.a,b=u.b,c=u.c,d=u.d; 60 b^=(1<<i); 61 a^=(1<<i); 62 c^=(1<<i); 63 if(i>0) 64 b^=(1<<(i-1)); 65 if(i<3) 66 b^=(1<<(i+1)); 67 if(!vis[a][b][c][d]){ 68 vis[a][b][c][d]=1; 69 q.push(node(a,b,c,d,u.t+1)); 70 } 71 } 72 for(int i=0;i<4;++i){ 73 a=u.a,b=u.b,c=u.c,d=u.d; 74 c^=(1<<i); 75 b^=(1<<i); 76 d^=(1<<i); 77 if(i>0) 78 c^=(1<<(i-1)); 79 if(i<3) 80 c^=(1<<(i+1)); 81 if(!vis[a][b][c][d]){ 82 vis[a][b][c][d]=1; 83 q.push(node(a,b,c,d,u.t+1)); 84 } 85 } 86 for(int i=0;i<4;++i){ 87 a=u.a,b=u.b,c=u.c,d=u.d; 88 d^=(1<<i); 89 c^=(1<<i); 90 if(i>0) 91 d^=(1<<(i-1)); 92 if(i<3) 93 d^=(1<<(i+1)); 94 if(!vis[a][b][c][d]){ 95 vis[a][b][c][d]=1; 96 q.push(node(a,b,c,d,u.t+1)); 97 } 98 } 99 } 100 printf("Impossible\n"); 101 } 102 int main() 103 { 104 for(int i=0;i<4;++i) 105 scanf("%s",p[i]); 106 bfs(); 107 return 0; 108 }
标签:
原文地址:http://www.cnblogs.com/20143605--pcx/p/4726068.html