【UVA1505】 Flood-it!(IDA*)

题目链接
IDA*,估价函数为当前除了左上角的连通块以外颜色的种类数,因为每次最多消去一个颜色。
维护位于当前连通块的边缘但颜色不同的点,每次从这些点拓展就行。

#include <cstdio>
#include <cstring>
int a[10][10], n, l[] = {-1, 1, 0, 0}, r[] = {0, 0, -1, 1}, v[10], vis[10][10], limit;
void dfs(int now, int x, int y){
	//printf("%d %d %d\n", now, x, y);
	vis[x][y] = 1;
	for(int i = 0; i < 4; ++i){
		int X = x + l[i], Y = y + r[i];
		if(X < 0 || Y < 0 || X >= n || Y >= n || vis[X][Y] == 1) continue;
		vis[X][Y] = 2;
		if(a[X][Y] == now) dfs(now, X, Y);
	}
} 
int fill(int now){
	int p = 0;
	for(int i = 0; i < n; ++i)
		for(int j = 0; j < n; ++j)
			if(a[i][j] == now && vis[i][j] == 2)
				dfs(now, i, j), ++p;
	return p;
}
int IDA(int now, int dep){
	v[0] = v[1] = v[2] = v[3] = v[4] = v[5] = 0;
	for(int i = 0; i < n; ++i)
		for(int j = 0; j < n; ++j)
			if(vis[i][j] != 1)
				v[a[i][j]] = 1;
	int f = v[0] + v[1] + v[2] + v[3] + v[4] + v[5];
	if(!f) return 1;
	if(dep + f > limit) return 0;
	int tmp[10][10];
	memcpy(tmp, vis, sizeof vis);
	for(int k = 0; k < 6; ++k){
		if(k == now) continue;
		if(fill(k) && IDA(k, dep + 1)) return 1;
		memcpy(vis, tmp, sizeof vis);
	}
	return 0;
}
int main(){
	while(scanf("%d", &n) && n){
		for(int i = 0; i < n; ++i)
			for(int j = 0; j < n; ++j)
				scanf("%d", &a[i][j]);
		memset(vis, 0, sizeof vis);
		dfs(a[0][0], 0, 0);
		for(limit = 0; ; ++limit){
			if(IDA(a[0][0], 0)){
				printf("%d\n", limit);
				break;
			}
		}
	}
}
posted @ 2019-08-13 09:00  Qihoo360  阅读(179)  评论(0编辑  收藏  举报
You're powerful!