您的位置:首页 > 其它

poj1753 DFS

2015-11-09 10:36 375 查看
利用DFS暴力枚举,没有什么特别的地方。枚举每一个点的状态。

#include<iostream>
using namespace std;
bool chess[6][6]={false};
int step;
bool flag;
int r[]= {-1,1,0,0,0};
int c[]= {0,0,-1,1,0};
bool judge_all(void)
{
for(int i=1; i<5; i++)
{
for(int j=1; j<5; j++)
{
if(chess[i][j]!=chess[1][1])
{
return false;
}
}
}
return true;
}
void filp(int row,int col)
{
for(int i=0; i<5; i++)
{
chess[row+r[i]][col+c[i]]=!chess[row+r[i]][col+c[i]];
}
return;
}
void dfs(int row,int col,int deep)
{
if(deep==step)
{
flag=judge_all();
return;
}
if(flag||row==5)
return;
filp(row,col);
if(col<4)
dfs(row,col+1,deep+1);
else
dfs(row+1,1,deep+1);
filp(row,col);
if(col<4)
dfs(row,col+1,deep);
else
dfs(row+1,1,deep);
return;
}
int main()
{
char temp;
for(int i=1; i<5; i++)
{
for(int j=1; j<5; j++)
{
cin>>temp;
if(temp=='b')
chess[i][j]=true;

}
}
for(step=0; step<=16; step++)
{
dfs(1,1,0);
if(flag)
{
break;
}
}
if(flag)
printf("%d\n",step);
else
printf("Impossible\n");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: