#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include < Queue>using namespace Std;int ch[20];int op[4][2]={1,0, -1,0, 0,1, 0,-1};int mat[200000];int vis[200000];void init_ch () {int i,j,k; int temp; int cnt=0; for (i=0;i<4;i++) {for (j=0;j<4;j++) {temp=0; Temp^= (1<< (3-i) *4+ (3-j)); for (k=0;k<4;k++) {int x=i+op[k][0]; int y=j+op[k][1]; if (x<0| | x>3| | y<0| | Y>3) continue; Temp^= (1<< (3-x) *4+ (3-y)); } ch[cnt++]=temp; }}}void Init_ans () {mat[0]=0; int i,j,k; Queue<int> Q; Q.push (0); while (!q.empty ()) {int Now=q.front (); int next; Vis[now] = 1; Q.pop (); for (i=0;i<16;i++) {next=now^ch[i]; if (vis[next]==0) {vis[next]=1; Mat[next]=mat[now]+1; Q.push (next); }}}}int Main () {int i,j,k; memset (vis,0,sizeof (VIS)); memset (Mat,-1,sizeof (MAT)); Init_ch (); Init_ans (); Char str[10][10]; while (scanf ("%s", Str[0])!=eof) {for (i=1;i<4;i++) {scanf ("%s", Str[i]); }/* for (i=0;i<4;i++) {printf ("%s\n", Str[i]); } printf ("\ n"); */int now=0,now1=0; for (i=0;i<4;i++) {for (j=0;j<4;j++) {now1<<=1; now<<=1; if (str[i][j]== ' B ') now+=1; if (str[i][j]== ' W ') now1+=1; printf ("%d%d\n", i,now); }}//now1=now^ (1<<16-1); int ans; if (vis[now]==0&&vis[now1]==0) {printf ("impossible\n"); } else if (vis[now]==0) {printf ("%d\n", Mat[now1]); } else if (vis[now1]==0) {printf ("%d\n", Mat[now]); } else printf ("%d\n", Min (Mat[now],mat[now1])); } return 0;}
POJ 1753 Flip Game (BFS)