POJ 1753 FLIP GAME——枚举深度的dfs

题目链接点击打开链接

题意:将白块翻成黑块或者将黑块翻成白块,在每一次反转时相邻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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值