poj 1753 Flip Game
http://poj.org/problem?id=1753
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
int bit[18],vis[70000] , value;
int mov[5][2]={0, 0, -1, 0, 1, 0, 0, 1, 0, -1};
char map[5][5];
struct node{
int v , step;
};
void init(){
int i, j;
value=0 ;
memset(vis, 0, sizeof(vis));
for(i=0 ;i< 4; i++){
for(j=0; j<4; j++){
if(map[i][j]=='b')
value|=bit[i*4+j];
}
}//cout<<"AA"<<value<<endl;
vis[value]=1;
}
void bfs(){
queue <node > q;
int i , j;
node head, start, next ;
head.v = value;
head.step = 0;
q.push(head);
while(!q.empty()){
int tx, ty, x, y;
head=q.front() ;
// printf("%d %d \n", head.v, head.step);
q.pop();
if(head.v ==0||head.v ==(0xffff)) {printf("%d\n",head.step);return ;}
next.step = head.step + 1;
for(i=0 ;i< 16; i++){
x=i/4;
y=i%4;
next.v= head.v ;
for(j =0; j<5; j++){
tx=x+mov[j][0];
ty=y+mov[j][1];
if(tx<0 || tx>=4 || ty<0 || ty>=4 ) continue;
next.v ^=bit[tx*4 + ty];
}
if(next.v ==0||next.v ==(0xffff)) {printf("%d\n",next.step);return ;}
if(!vis[next.v]) {
vis[next.v]=1;
q.push(next);
}
}
}
printf("Impossible\n");
}
int main(){
// freopen("1.txt", "r", stdin);
int i, j;
for(i=0; i<16; i++){
bit[i]= 1<<i ;//cout<<bit[i]<<" ";
}
while(scanf("%s%s%s%s",map[0], map[1], map[2], map[3] )!=EOF){
init();
bfs();
}
return 0;
}