Problem Description
Flood-it is a fascinating puzzle game on Google+ platform. The game interface is like follows:
At the beginning of the game, system will randomly generate an N×N square board and each grid of the board is painted by one of the six colors. The player starts from the top left corner. At each step, he/she selects a color and changes all the grids connected with the top left corner to that specific color. The statement “two grids are connected” means that there is a path between the certain two grids under condition that each pair of adjacent grids on this path is in the same color and shares an edge. In this way the player can flood areas of the board from the starting grid (top left corner) until all of the grids are in same color. The following figure shows the earliest steps of a 4×4 game (colors are labeled in 0 to 5):
Given a colored board at very beginning, please find the minimal number of steps to win the game (to change all the grids into a same color).
Input
The input contains no more than 20 test cases. For each test case, the first line contains a single integer N (2<=N<=8) indicating the size of game board.
The following N lines show an N×N matrix (ai,j)n×n representing the game board. ai,j is in the range of 0 to 5 representing the color of the corresponding grid.
The input ends with N = 0.
Output
For each test case, output a single integer representing the minimal number of steps to win the game.
Sample Input
2
0 0
0 0
3
0 1 2
1 1 2
2 2 1
0
Sample Output
0
3
/*from: https://blog.csdn.net/weizhuwyzc000/article/details/47345573*/
#include<bits/stdc++.h>
using namespace std;
const int maxn = 15;
int n,maxd,a[maxn][maxn];
int vis[maxn][maxn];
int dx[] = { 0,1,0,-1,1,-1,-1,1 };
int dy[] = { 1,0,-1,0,1,-1,1,-1 };
void dfs2(int r,int c,int col) { //更新vis[i][j]数组,给vis[i][j] == 2的变成1,与之相邻的变成2
vis[r][c] = 1;
for(int i=0;i<4;++i) {
int x = r+dx[i];
int y = c+dy[i];
if(x < 0 || x >=n || y < 0 || y >= n ) continue;
if(vis[x][y] == 1 ) continue;
vis[x][y] = 2;
if(a[x][y] == col)
dfs2(x,y,col);
}
}
int H() {
int maze[8],cnt = 0;
memset(maze,0,sizeof(maze));
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(vis[i][j]==1) continue;
if(!maze[a[i][j]]) { maze[a[i][j]]++; cnt++; }
}
}
return cnt;
}
int filled(int col) {
int cnt = 0;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++){
if(a[i][j] != col) continue;
if(vis[i][j] == 2) { //只有当vis[i][j] == 2且与col同色的才染色
cnt++;
dfs2(i,j,col);
}
}
return cnt;//返回染色的个数
}
bool dfs(int d) {
if(d == maxd) return H()==0;
if( ( H() + d ) > maxd ) return false;
int vi[maxn][maxn];
memcpy(vi,vis,sizeof(vi));
for(int i=0;i<6;i++) {
if(filled(i) == 0) continue; //没有符合要求的i颜色的块与之相邻
if(dfs(d+1)) return true;
memcpy(vis,vi,sizeof(vis));
}
return false;
}
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));
dfs2(0,0,a[0][0]);
for(maxd = 0; ; ++maxd)
if(dfs(0)) break;
printf("%d\n",maxd);
}
return 0;
}