You are given a two-dimensional table (grid) A of N rows and M columns. Every cell contains a lowercase letter, one of 'a' - 'z'.
Let's call two cells of A adjacent, if they share a common side.
Let's call a set S of cells a connected region if the following three conditions are satisfied:
Every side of a cell is also called a side of the table. Let's call a side of the table inner, if it separates two adjacent cells. In a similar way, let's call a side of the table outer, if it lies on the border of the table.
For example, for a table of N=3 rows and M=4 columns, the blue sides are outer and the red sides are inner:
Let's say, that a connected region S is completely inside another connected region T, if there's a cycle path of adjacent cells of T, such that all the cells of S are inside the contour (shape), formed by the cycle path.
It's guaranteed that in the input no connected region is completely inside some other connected region.
Your task is to split A into a set of connected regions, separating each connected region from the others. You are allowed to pick some set of paths along inner sides of the table, that separate different connected regions, and make a cut along each of the paths.
Please, read the sample explanation to understand the problem better.
It can be proved that it's always possible to split the table as described above. Can you find the minimum number of paths to do so?
The first line contains one integer T denoting the number of test cases in the input.
The first line of each test case description contains two integers N and M denoting the number of rows and the number of columns in A respectively.
Each of the next N lines contains a string of M lowercase letters, each denoting one row of the table A.
It's guaranteed that no connected region is completely inside some other connected region.
For each test case, in a separate line output the minimum number of paths to split the table the way described above.
Extra constraints | Points | Which tests |
---|---|---|
N=1 | 30 | 1 |
no extra constraints | 70 | 2 |
The first test case of the sample input:
There are five connected regions. The inner sides, that must be cut in the sample input, are colored red on the picture:
It can be done picking two paths, as shown on the picture below (the first path is colored red, the second one is colored blue):
Stack Limit for C++ is 8MB. You are allowed to increase it in your code, e.g. using setrlimit().