# poj1753（BFS+位储存）

www.MyException.Cn  网友分享于：2014-03-17  浏览：2次
poj1753（BFS+位存储）

```#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = (1<<16)-1;
int v[N+5],state,flag;
int judge(char c)
{
if(c == 'b')
return 1;
else
return 0;
}
int cal(int state, int pos)
{
state ^= (1<<pos);//自身取反，变色
if(pos >= 4)//上
state ^= (1<<(pos-4));
if(pos <= 11)//下
state ^= (1<<(pos+4));
if(pos%4 != 0)//左
state ^= (1<<(pos-1));
if(pos%4 != 3)//右
state ^= (1<<(pos+1));
return state;
}
void bfs()
{
memset(v, -1, sizeof(v));
v[state] = 0;
queue <int> q;
q.push(state);
while(!q.empty())
{
int tmp = q.front();
q.pop();
for(int i = 0; i < 16; i ++)//枚举，改变每一枚棋子的颜色
{
state = cal(tmp, i);
if(v[state] != -1) continue;//状态已经出现过
if(state == 0 || state == N)
{
printf("%d\n",v[tmp] + 1);
flag = 1;
return;
}
v[state] = v[tmp] + 1;
q.push(state);
}
}
}
int main()
{
int i,j,k = 0;
char a[10];
state = 0;
for(i = 0; i < 4; i++)
{
scanf("%s",a);
for(j = 0; j < 4; j ++, k ++)
{
state += (judge(a[j]))<<k;//初始状态
}
}
if(state == 0 || state == N)
{
printf("0\n");
return 0;
}
flag = 0;
bfs();
if(!flag)
printf("Impossible\n");
return 0;
}
```