POJ1753

Written by    18:25 June 17, 2014 

原题POJ1753

Flip Game
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 36003 Accepted: 15706

Description

Flip game is played on a rectangular 4×4 field with two-sided pieces placed on each of its 16 squares. One side of each piece is white and the other one is black and each piece is lying either it’s black or white side up. Each round you flip 3 to 5 pieces, thus changing the color of their upper side from black to white and vice versa. The pieces to be flipped are chosen every round according to the following rules:

  1. Choose any one of the 16 pieces.
  2. Flip the chosen piece and also all adjacent pieces to the left, to the right, to the top, and to the bottom of the chosen piece (if there are any).

Consider the following position as an example:

bwbw
wwww
bbwb
bwwb
Here “b” denotes pieces lying their black side up and “w” denotes pieces lying their white side up. If we choose to flip the 1st piece from the 3rd row (this choice is shown at the picture), then the field will become:

bwbw
bwww
wwwb
wwwb
The goal of the game is to flip either all pieces white side up or all pieces black side up. You are to write a program that will search for the minimum number of rounds needed to achieve this goal.

Input

The input consists of 4 lines with 4 characters “w” or “b” each that denote game field position.

Output

Write to the output file a single integer number – the minimum number of rounds needed to achieve the goal of the game from the given position. If the goal is initially achieved, then write 0. If it’s impossible to achieve the goal, then write the word “Impossible” (without quotes).

Sample Input

Sample Output

Source

这一道题最关键的部分就是运用了DFS算法(Depth-First Search, 深度优先搜索算法)

首先来看其它几个比较简单的函数

初始化函数,输入棋盘

赋反值函数:

翻转函数:

检测函数:

上面的函数都比较简单,几乎不用什么脑子想,最关键的就是dfs函数

虽然数据结构早就学了DFS,但是一直都不是特别理解,听了前辈的建议,把算法用笔在纸上模拟了一遍果然就明了了。 DFS算法其实就是先到达最深处的点,然后一步一步往回走,每一步再往下一步一步看,在这道题里面首先到最远的id为16的点,然后尝试所有的的翻转可能,每到一个点向下就有2^(17-id)种可能, 然后遍历一遍。 我后来又把程序改了一下,把每一次翻转都打印一遍,这样就更清晰更好理解了,只用把flip函数修改一下即可。 PS: 这里最好把col改小一点好模拟一些, col等于4的时候翻转了13+w次, 改成2就可以了, 只有28次。

完整代码:

Category : acmstudy

Tags :