棋盘染色(迭代加深搜索)

棋盘染色

题目描述:
有一个5×5的棋盘,上面有一些格子被染成了黑色,其他的格子都是白色,你的任务的对棋盘一些格子进行染色,使得所有的黑色格子能连成一块,并且你染色的格子数目要最少。读入一个初始棋盘的状态,输出最少需要对多少个格子进行染色,才能使得所有的黑色格子都连成一块。(注:连接是指上下左右四个方向,如果两个黑色格子只共有一个点,那么不算连接)
输入描述:
输入包括一个5×5的01矩阵,中间无空格,1表示格子已经被染成黑色。
输出描述:
输出最少需要对多少个格子进行染色
样例输入:
11100
11000
10000
01111
11111
样例输出:
1

#include<iostream>
#include<cstring>
using namespace std;
const int maxn=6;
int sx[5]={0,0,1,0,-1},
    sy[5]={0,1,0,-1,0};
int n,fx,fy,tot,total,map[maxn][maxn],f[maxn][maxn];
void power_can(int x,int y)
{
    tot++; f[x][y]=1;
    for(int i=1;i<=4;i++)
    {
        int fx=x+sx[i];
        int fy=y+sy[i];
        if(fx>=1&&fx<=5&&fy>=1&&fy<=5&&!f[fx][fy]&&map[fx][fy])
        power_can(fx,fy);
    }
}
int can(int x)
{
    tot=0; memset(f,0,sizeof(f));
    power_can(fx,fy);
    if(tot==total+x)
    return 1; return 0;
}
int power_dfs(int x,int y,int now,int sum)
{
    if(now==sum)
    {
        if(can(sum))
        return 1;
        return 0;
    }
    for(int j=y+1;j<=5;j++)
    if(!map[x][j])
    {
        map[x][j]=1;
        if(power_dfs(x,j,now+1,sum)) return 1;
        map[x][j]=0;
    }
    for(int i=x+1;i<=5;i++)
      for(int j=1;j<=5;j++)
      if(!map[i][j])
      {
        map[i][j]=1;
        if(power_dfs(i,j,now+1,sum)) return 1;
        map[i][j]=0;
      }
    return 0;
}
int main()
{
    for(int i=1;i<=5;i++)
    {
        char c;
        for(int j=1;j<=5;j++)
        {
            cin>>c;
            map[i][j]=c-'0';
            if(map[i][j]==1)
            {
                total++;
                fx=i,fy=j;
            }
        }
    }
    for(int i=0;i<=5*5;i++)
    if(power_dfs(0,0,0,i))//横坐标,纵坐标,以染了多少,一共染多少(迭代加深) 
    {
        cout<<i;
        return 0;
    }
}
原文地址:https://www.cnblogs.com/cax1165/p/6070982.html