ZOJ 3781 Paint the Grid Reloaded ( BFS(重点是对问题的分析) )

来源:互联网 发布:v家歌曲知乎 编辑:程序博客网 时间:2024/05/16 15:03

题目链接

Paint the Grid Reloaded

Time Limit: 2 Seconds      Memory Limit: 65536 KB

Leo has a grid with N rows and M columns. All cells are painted with either black or white initially.

Two cells A and B are called connected if they share an edge and they are in the same color, or there exists a cellC connected to both A and B.

Leo wants to paint the grid with the same color. He can make it done in multiple steps. At each step Leo can choose a cell and flip the color (from black to white or from white to black) of all cells connected to it. Leo wants to know the minimum number of steps he needs to make all cells in the same color.

Input

There are multiple test cases. The first line of input contains an integer T indicating the number of test cases. For each test case:

The first line contains two integers N and M (1 <= N, M <= 40). Then N lines follow. Each line contains a string withN characters. Each character is either 'X' (black) or 'O' (white) indicates the initial color of the cells.

Output

For each test case, output the minimum steps needed to make all cells in the same color.

Sample Input

22 2OXOX3 3XOXOXOXOX

Sample Output

12

Hint

For the second sample, one optimal solution is:

Step 1. flip (2, 2)

XOXOOOXOX

Step 2. flip (1, 2)

XXXXXXXXX

这题终点是分析的思维,很难看出这个问题的本质。

题意:每次操作选择一个点,将与它联通的相同的点取反,问最少多少次能够让整个图都是一样的?

题解:将联通块缩点,那么问题就转换为,选择一个点为起点,使得离这个点最远的点的距离最小。直接bfs即可。

0 0