POJ4007 IDA*

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
#define rep(i,l,p) for(int i=l;i<=p;i++)
#define mp make_pair
typedef pair<int,int> P;
const int dx[4]={0,0,1,-1},dy[4]={1,-1,0,0};
const int N = 1e5+5;
int n;
int a[10][10];
int vis[10][10];
void dye(int x,int y,int c){
    vis[x][y] = 1;
    rep(i,0,3){
        int tx = x+dx[i],ty = y+dy[i];
        if(a[tx][ty] == -1 || vis[tx][ty] == 1) continue;
        if(a[tx][ty] == c) dye(tx,ty,c);
        else vis[tx][ty] = 2;
    }
}
int used[6];
int g(){
    memset(used,0,sizeof used);
    int res = 0;
    rep(i,1,n){
        rep(j,1,n){
            if(vis[i][j]!=1 && used[a[i][j]] == 0){
                res++; used[a[i][j]] = 1;
            }
        }
    }
    return res;
}
int T;
bool cnt(int c){
    int res = 0;
    rep(i,1,n){
        rep(j,1,n){
            if(vis[i][j] == 2&&a[i][j] == c){
                dye(i,j,c);
                res++;
            }
        }
    }
    return res;
}
bool A_star(int dep){
    if(dep == T) if(g()==0) return true;
    if(dep + g() > T) return false;
    for(int i=0;i<=5;i++){
        int tmp[10][10];
        rep(i,1,n){
            rep(j,1,n){
                tmp[i][j] = vis[i][j];
            }
        }
        if(!cnt(i)) continue;
        if(A_star(dep+1)) return true;
        rep(i,1,n){
            rep(j,1,n){
                vis[i][j] = tmp[i][j];
            }
        }
    }
    return false;
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    while(cin >> n && n){
        memset(vis,-1,sizeof vis);
        memset(a,0,sizeof a);
        rep(i,0,n+1) a[0][i] = a[i][0] =a[n+1][i] = a[i][n+1] = -1;
        rep(i,1,n){
            rep(j,1,n){
                cin >> a[i][j];
            }
        }
        dye(1,1,a[1][1]);
        for(T = g();;T++){
          //  cout <<"?" << endl;
            if(A_star(0)){
                cout << T << endl;
                break;
            }
        }
    }
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值