浙大ACM 1008题 不会 ,求助,有什么好的思路么
原题地址:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1008
原题:Hart is engaged in playing an interesting game, Gnome Tetravex, these days. In the game, at the beginning, the player is given n*n squares. Each square is divided into four triangles marked four numbers (range from 0 to 9). In a square, the triangles are the left triangle, the top triangle, the right triangle and the bottom triangle. For example, Fig. 1 shows the initial state of 2*2 squares.
Fig. 1 The initial state with 2*2 squares
The player is required to move the squares to the termination state. In the termination state, any two adjoining squares should make the adjacent triangle marked with the same number. Fig. 2 shows one of the termination states of the above example.
Fig. 2 One termination state of the above example
It seems the game is not so hard. But indeed, Hart is not accomplished in the game. He can finish the easiest game successfully. When facing with a more complex game, he can find no way out.
One day, when Hart was playing a very complex game, he cried out, "The computer is making a goose of me. It's impossible to solve it." To such a poor player, the best way to help him is to tell him whether the game could be solved. If he is told the game is unsolvable, he needn't waste so much time on it.
Input
The input file consists of several game cases. The first line of each game case contains one integer n, 0 <= n <= 5, indicating the size of the game.
The following n*n lines describe the marking number of these triangles. Each line consists of four integers, which in order represent the top triangle, the right triangle, the bottom triangle and the left triangle of one square.
After the last game case, the integer 0 indicates the termination of the input data set.
Output
You should make the decision whether the game case could be solved. For each game case, print the game number, a colon, and a white space, then display your judgment. If the game is solvable, print the string "Possible". Otherwise, please print "Impossible" to indicate that there's no way to solve the problem.
Print a blank line between each game case.
Note: Any unwanted blank lines or white spaces are unacceptable.
Sample Input
2
5 9 1 4
4 4 5 6
6 8 5 4
0 4 4 3
2
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
0
Output for the Sample Input
Game 1: Possible
Game 2: Impossible
大意就是先输入规模 n (0<=n<=5),然后输入n*n个方块,每个方块有4个数字,位于方块的上下左右。
然后我们可以随意移动这些方块,使得每个相邻的方块上的相邻的数字是一样的。
不需要给出移动结果,只需判断能否移动成功。 acm 浙大acm
[解决办法]
数据范围这么小,一般硬搜。
[解决办法]
回溯算法即可。 从左上角到右下角依次编号0..n^2-1,
1. 设置i = 0, A(0)=所有方块, 将0号块放在0号位置
2. i++, 如果i=n^2, 则输出Possible
3. 否则, 在未放置方块中找出能放在位置i的所有方块的集合A(i)
4. 如A(i)非空, 则取编号最小的放置在位置i上, 返回第2步
5. 如A(i)为空,进行回溯.
1) i--, 如i < 0, 则输出Impossible
2) 在位置i上更换成A(i)中的下一个元素, 如该元素存在返回第2步, 该元素不存在返回第5步