解法: 题目中一个8*8的矩阵,只有6种颜色染色,很容易想到最糟糕的情况也不可能会需要64步,反而由于颜色的数量限制,答案很可能很小,而又没有什么规律在,那么第一眼就想到了迭代加深搜索,即,由小到大枚举答案,若可行则为最小解,主体用dfs搜索,用bfs进行染色,8*8的格子使得可以把图压缩到一个long long 整型,但是还需要一个看似不起眼的剪枝,否则TLE到哭: 当剩下未染的格子的颜色种数大于剩下的染色次数时,直接放弃对该子树的搜索。
虽然这个剪枝在颜色数只有6的情况下看似鸡肋,但是不然,因为在深度优先搜索的过程中,前n-1层相对于第n层都可以忽略,那么一次剪掉6层。。。效果可想而知。这里的大意导致比赛时不能AC,真是爽。。
搜索的魅力(kengdie)大概在于,莫名其妙的剪枝,莫名其妙的AC。。
/* Created Time: Wednesday, November 06, 2013 PM02:06:50 CST */
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
typedef long long lld;
const int N = 8;
int n,col[N][N],sa[6];
lld all;
int dir[4][2] = {1,0,0,1,-1,0,0,-1};
bool exist(lld st,int x,int y) {
return st&(1ll<<(x*n+y));
}
void show(lld st) {
for (int i = 0; i < n; i ++) {
for (int j = 0; j < n; j ++)
printf("%d ",exist(st,i,j));
puts("");
}
puts("");
}
int que[110],qf,qe;
int cover(lld og,lld &st,int c) {
int cnt[6] = {0};
qf = 0;
qe = -1;
que[++qe] = 0;
st = 1;
cnt[col[0][0]] ++;
while (qf<=qe) {
int f = que[qf++];
int x = f/n,y = f%n;
for (int i = 0; i < 4; i ++) {
int ex = x+dir[i][0];
int ey = y+dir[i][1];
if (ex<0 || ex>=n ||ey<0 || ey>=n) continue;
if (exist(st,ex,ey)) continue;
if (exist(og,ex,ey) || col[ex][ey]==c) {
cnt[col[ex][ey]] ++;
st |= 1ll<<(ex*n+ey);
que[++qe] = ex*n+ey;
}
}
}
int ret = 0;
for (int i = 0; i < 6; i ++)
if (sa[i]-cnt[i]) ret ++;
return ret;
}
bool dfs(lld st,int cur) {
if (cur==0) {
return st==all;
}
for (int i = 0; i < 6; i ++) {
lld bst = 0;
int left = cover(st,bst,i);
if (st==bst || left>cur-1) continue;
if (dfs(bst,cur-1)) return true;
}
return false;
}
int work() {
all = 0;
for (int i = 0; i < n; i ++)
for (int j = 0; j < n; j ++)
all |= 1ll<<(i*n+j);
lld st = 0;
cover(0,st,col[0][0]);
for (int i = 0; i <= n*n; i ++) {
if (dfs(st,i)) return i;
}
return -1;
}
int main() {
while (~scanf("%d",&n),n) {
memset(sa,0,sizeof(sa));
for (int i = 0; i < n; i ++)
for (int j = 0; j < n; j ++) {
scanf("%d",&col[i][j]);
sa[col[i][j]] ++;
}
printf("%d\n",work());
}
return 0;
}