题目链接点击打开链接
题意:将白块翻成黑块或者将黑块翻成白块,在每一次反转时相邻4个也会翻转,问最少需要翻转多少次使得棋盘上的棋子清一色。
思路:这是一道搜索题,对于每个棋子,翻或不翻。一共有2^16种情况。最多需要翻转16步,面对一道看似没有深度的树进行搜索,要找到最少的步数,只需枚举0—16的深度即可。这种方法在刘汝佳白书中有提到。但是我看书不精,后来是看了网上解题报告,才意识到这种方法的。
AC代码
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<iomanip>
#include<algorithm>
#include<cmath>
using namespace std;
int step,flag;
bool a[5][5];
int dir[5][2]= {{1,0},{-1,0},{0,1},{0,-1},{0,0}};
bool judge()//判断同色
{
int i,j;
for(i=0; i<4; i++)
{
for(j=0; j<4; j++)
if(a[i][j]!=a[0][0])
return false;
}
return true;
}
void flip(int x,int y)//翻翻~~~
{
for(int i=0; i<5; i++)
{
int tmpx=x+dir[i][0];
int tmpy=y+dir[i][1];
if(tmpx>=0 && tmpx<4 && tmpy>=0 && tmpx<4)
{
a[tmpx][tmpy]=!a[tmpx][tmpy];
}
}
}
void dfs(int x,int y,int cnt)
{
if(cnt==step)
{
flag=judge();
return ;
}
if(flag || y==4 ) return;
flip(x,y);
if(x+1<4) dfs(x+1,y,cnt+1);
else dfs(0,y+1,cnt+1);
if(!flag)
{
flip(x,y);
if(x+1<4) dfs(x+1,y,cnt);
else dfs(0,y+1,cnt);
}
}
int main()
{
int i,j;
memset(a,0,sizeof(a));
flag=0;
char tmp;
for(i=0; i<4; i++)
{
for(j=0; j<4; j++)
{
cin>>tmp;
if(tmp=='b')
a[i][j]=true;
}
}
for(step=0; step<=16; step++)
{
dfs(0,0,0);
if(flag)
{
cout<<step<<endl;
break;
}
}
if(!flag) cout<<"Impossible\n";
return 0;
}