

Floodit!Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2401 Accepted Submission(s): 658 Problem Description Floodit 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 (a_{i,j})_{n×n} representing the game board. a_{i,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
Sample Output
Source  
