# Include <iostream> # include <cstdio> # include <cstring> # include <queue> # define maxn 10 # define INF 0x3f3f3fusing namespace std; int n, m, ans, flag, depth; int mp [maxn] [maxn]; int dx [] = {-,}; int dy [] = }; bool vis [maxn] [maxn]; struct Node {int x, y;} cur, now, q [100]; struct node {int num; node xx [100] ;}; void bfs (node & tt, int color []) {int I, j, nx, ny, tx, ty; int head = 0, tail =-1; tt. num = 0; memset (vis, 0, s Izeof (vis); cur. x = cur. y = 1; vis [1] [1] = 1; q [++ tail] = cur; while (head <= tail) {now = q [head]; head ++; tt. xx [++ tt. num] = now; nx = now. x; ny = now. y; for (I = 0; I <4; I ++) {tx = nx + dx [I]; ty = ny + dy [I]; if (tx <1 | tx> n | ty <1 | ty> n | vis [tx] [ty] | mp [tx] [ty]! = Mp [nx] [ny]) continue; cur. x = tx; cur. y = ty; vis [tx] [ty] = 1; q [++ tail] = cur ;}} for (I = 1; I <= n; I ++) // remaining colors of the tag {for (j = 1; j <= n; j ++) {if (! Vis [I] [j]) color [mp [I] [j] = 1 ;}} void dfs (int c, int cnt, int step) // number of steps of the current color connected block size {if (step> depth | flag) return; // return int I, j, t = 0, num, color [6] = {0}; node tt; bfs (tt, color); num = tt. num; if (num <= cnt) return; // make sure to search for (I = 0; I <6; I ++) in multiple directions each time) // calculate the remaining colors {t + = color [I];} if (step + t> depth) return; // number of current steps + remaining colors> depth return if (num = n * n) {flag = 1; ans = step; return ;}for (I = 0; I <6; I ++) {I F (I = c) continue; for (j = 1; j <= num; j ++) // change the color {mp [tt. xx [j]. x] [tt. xx [j]. y] = I;} dfs (I, num, step + 1); for (j = 1; j <= num; j ++) // restored color {mp [tt. xx [j]. x] [tt. xx [j]. y] = c ;}} void IDA () {int I, j; flag = 0; depth = 1; while (! Flag) {dfs (mp [1] [1], 0, 0); depth ++ ;}} int main () {int I, j; while (scanf ("% d", & n), n) {for (I = 1; I <= n; I ++) {for (j = 1; j <= n; j ++) {scanf ("% d", & mp [I] [j]) ;}} ans = INF; IDA (); printf ("% d \ n", ans);} return 0 ;}