
ZOJ Problem Set  3781
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. InputThere 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. OutputFor each test case, output the minimum steps needed to make all cells in the same color. Sample Input2 2 2 OX OX 3 3 XOX OXO XOX Sample Output1 2 HintFor the second sample, one optimal solution is: Step 1. flip (2, 2) XOX OOO XOX Step 2. flip (1, 2) XXX XXX XXX Author: YU, Xiaoyao Source: The 11th Zhejiang Provincial Collegiate Programming Contest 