您的位置:首页 > 其它

POJ-1753

2016-05-08 20:42 260 查看
题目链接:http://poj.org/problem?id=1753

题目概述:有4*4的正方形,每个格子要么是黑色,要么是白色,当把一个格子的颜色改变(黑->白或者白->黑)时,其周围上下左右(如果存在的话)的格子的颜色也被反转,问至少反转几个格子可以使4*4的正方形变为纯白或者纯黑?

#include"iostream"
using namespace std;

bool qipan[6][6]={false};
bool flag;
int  a[]={-1,1,0,0,0};
int  b[]={0,0,-1,1,0};
int step;
bool panduan(){
for(int i=1;i<=4;i++)
for(int j=1;j<=4;j++)
if(qipan[i][j]!=qipan[1][1])
return false;
return true;
}
void bianhuan(int c,int d){
for(int i=0;i<5;i++)
qipan[c+a[i]][d+b[i]]=!qipan[c+a[i]][d+b[i]];
}
void dfs(int row,int tow,int deep){
if(deep==step){
flag=panduan();
return;
}
if(row||tow==5)
return;
bianhuan(row,tow);
if(row<4)
dfs(row,tow+1,deep+1);
else
dfs(row+1,tow,deep+1);
bianhuan(row,tow);
if(row<4)
dfs(row,tow+1,deep);
else
dfs(row+1,tow,deep);
return;
}
int main(){
char temp;
int i,j;
for(i=1;i<5;i++)
for(j=1;j<5;j++)
{
cin>>temp;
if(temp=='b')
qipan[i][j]=true;
}

for(step=0;step<=16;step++)  //对每一步产生的可能性进行枚举
{                            //至于为什么是16,考虑到4x4=16格,而每一格只有黑白两种情况,则全部的可能性为2^16
dfs(1,1,0);
if(flag)break;
}

if(flag)
cout<<step<<endl;
else
cout<<"Impossible"<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: