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 cell C 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 with N 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
2 2 2 OX OX 3 3 XOX OXO XOX
Sample Output
1 2
Hint
For the second sample, one optimal solution is:
Step 1. flip (2, 2)
XOX OOO XOX
Step 2. flip (1, 2)
XXX XXX XXX
这题终点是分析的思维,很难看出这个问题的本质。
题意:每次操作选择一个点,将与它联通的相同的点取反,问最少多少次能够让整个图都是一样的?
题解:将联通块缩点,那么问题就转换为,选择一个点为起点,使得离这个点最远的点的距离最小。直接bfs即可。