1.链接地址
https://vjudge.net/problem/POJ-1753
2.问题描述
烤烤最喜欢抛硬币了!他专门淘宝了一盒4X4的硬币盒, 盒子上放有16枚硬币,每枚硬币有正反两个不同的面 每次烤烤可以选择一枚硬币,并将这枚硬币和它上下左右相邻的硬币(如果有的话)翻一面~ 给定盒子里硬币初始状态,请问在一些操作后,他是否可以将所有硬币都翻成一个面?如果可以的话,最少需要多少步操作?(翻一枚硬币和其所有相邻的硬币总共算一次操作)
输入样例
bwwb bbwb bwwb bwww
输出样例
4
3.解题思路
一般来讲,递归枚举可以用于数据量较大,若一一列举容易遗漏的情况,因此解这道题可以使用了递归枚举的思想,先将所有棋子从头到尾压入栈,再从最后一个入栈的棋子开始,先把它拿出来,翻转后判断棋子是否一致,不一致则把倒数第二个拿出来。。。理解递归枚举的概念后理解这道题的做法不难
4.算法实现源代码
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
int map[10][10];
int ans;
int check()
{
int x=map[0][0];
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
{
if(map[i][j]!=x)
{
return 0;
}
}
}
return 1;
}
void fan (int x,int y)
{
map[x][y]=!map[x][y];
if (x - 1 >= 0)
map[x-1][y]=!map[x-1][y];
if (x + 1 < 4)
map[x+1][y]=!map[x+1][y];
if (y - 1 >= 0)
map[x][y-1]=!map[x][y-1];
if (y + 1 < 4)
map[x][y+1]=!map[x][y+1];
}
int dfs(int x,int y,int t)
{
if(check())
{
if(ans>t)
{
ans=t;
}
return 0;
}
if(x>=4||y>=4)
{
return 0;
}
int nx=(x+1)%4;
int ny=y+(x+1)/4;
dfs(nx,ny,t);
fan(x,y);
dfs(nx,ny,t+1);
fan(x,y);
return 0;
}
int main()
{
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
{
char c;
cin>>c;
if(c=='b')
{
map[i][j]=1;
}
else if(c=='w')
{
map[i][j]=0;
}
}
}
ans=1e9;
dfs(0,0,0);
if(ans==1e9)
{
cout<<"Impossible"<<endl;
}
else
{
cout<<ans<<endl;
}
}