题意:给n*n的方格,每个格子有一种颜色(0~5),每次可以选择一种颜色,使得和左上角相连(颜色相同以及相邻,间接也行)的所有的格子都为该颜色。求最少的步数,使得所有的方格颜色都相同。
思路:搜索。直接bfs搜索肯定不行,状态太多会爆掉内存,考虑用IDA*搜索。直接在原图上搜索比较麻烦,所以我们考虑建一个新图,这也是这道题的关键,用1表示当前格子与(1,1)处于一个颜色的连通块中,2表示与之前那个连通块相邻但颜色不同的格子,0表示其他格子,然后就可以搜索了,估价函数是剩余的0中还有多少种颜色,用这个来表示至少还要走多少步,用这个数和当前深度来剪枝。
ps:一开始这道题的剪枝条件写错了,少加了1,结果一直tle,改了以后ac。这也说明了IDA*效率还是很高的,剪枝的作用也很明显,少加了1就会t。
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#include<string>
#include<map>
#include<set>
#include<ctime>
#define eps 1e-6
#define LL long long
#define pii pair<int, int>
//#pragma comment(linker, "/STACK:1024000000,1024000000")
using namespace std;
const int dx[] = {-1, 0, 1, 0};
const int dy[] = {0, 1, 0, -1};
int n;
int G[10][10], newG[10][10];
bool check() {
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
if(newG[i][j] != 1) return false;
return true;
}
void dfs(int x, int y, int v) {
newG[x][y] = 1;
for(int i = 0; i < 4; i++) {
int nx = x + dx[i], ny = y + dy[i];
if(nx<1 || nx>n || ny<1 || ny>n || newG[nx][ny]) continue;
if(G[nx][ny] == v) dfs(nx, ny, v);
else newG[nx][ny] = 2;
}
}
bool update(int v) {
bool tag = 0;
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++) {
if(newG[i][j]==2 && G[i][j]==v) {
tag = 1;
dfs(i, j, v);
}
}
}
return tag;
}
int cost() {
int cnt[6] = {0}, ans = 0;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
if(!newG[i][j]) cnt[G[i][j]]++;
for(int i = 0; i < 6; i++)
if(cnt[i]) ans++;
return ans;
}
bool IDAstar(int dep, int maxd) {
if(dep == maxd) {
if(check()) return true;
return false;
}
int tmp[10][10];
memcpy(tmp, newG, sizeof(newG));
for(int i = 0; i < 6; i++) {
if(update(i)) {
if(dep+1+cost() > maxd) memcpy(newG, tmp, sizeof(newG));
else {
if(IDAstar(dep+1, maxd)) return true;
memcpy(newG, tmp, sizeof(newG));
}
}
}
return false;
}
int main() {
//freopen("input.txt", "r", stdin);
while(cin>>n && n) {
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++) scanf("%d", &G[i][j]);
memset(newG, 0, sizeof(newG));
newG[1][1] = 2;
update(G[1][1]);
int ans = 0;
for(int maxd = 0; ; maxd++) {
if(IDAstar(0, maxd)) {
ans = maxd;
break;
}
}
cout << ans << endl;
}
return 0;
}