网上说是枚举,我却用了BFS搜索的。
看到discuss上说用位运算可以解决,代码很短,好神奇,有空研究下。。
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<queue>
using namespace std;
struct State
{
bool grid[6][6];
int step;
};
void Change(State &tmp,int x,int y)
{
tmp.grid[x][y]=!tmp.grid[x][y];
tmp.grid[x-1][y]=!tmp.grid[x-1][y];
tmp.grid[x+1][y]=!tmp.grid[x+1][y];
tmp.grid[x][y-1]=!tmp.grid[x][y-1];
tmp.grid[x][y+1]=!tmp.grid[x][y+1];
}
int Convers(State tmp)
{
int ans=0;
for(int i=1; i<=4; ++i)
for(int j=1; j<=4; ++j)
ans=ans*2+tmp.grid[i][j];
return ans;
}
bool vis[100000];
int main()
{
char str[5];
State st;
for(int i=1; i<=4; ++i)
{
gets(str);
for(int j=0; str[j]; ++j)
if(str[j]=='b') st.grid[i][j+1]=1;
else st.grid[i][j+1]=0;
}
memset(vis,0,sizeof(vis));
int val=Convers(st);
if(val==0||val==65535)
printf("0\n");
else
{
int ans;
bool ok=false;
st.step=0;
vis[val]=true;
queue<State> q;
q.push(st);
while(!q.empty()&&!ok)
{
State tmp=q.front();
q.pop();
for(int i=1; i<=4; ++i)
for(int j=1; j<=4; ++j)
{
State t=tmp;
Change(t,i,j);
int vv=Convers(t);
if(vis[vv]) continue;
else
{
vis[vv]=true;
t.step++;
if(vv==0||vv==65535)
{
ans=t.step;
ok=true;
break;
}
q.push(t);
}
}
}
if(!ok) puts("Impossible");
else printf("%d\n",ans);
}
return 0;
}