#K37527. Count Color Regions
Count Color Regions
Count Color Regions
You are given a 2D grid of characters, where each cell represents a color. Two cells are considered connected if they are adjacent horizontally or vertically and have the same color. A region is a maximal set of connected cells of the same color.
Your task is to count the number of distinct regions in each grid.
The connectivity can be expressed mathematically as: Two cells at positions \((i,j)\) and \((k,l)\) are connected if $$|i-k|+|j-l|=1$$ and they share the same color.
Input: The input consists of multiple test cases. The first line contains an integer \(T\) which denotes the number of test cases. For each test case, the first line contains two integers \(N\) and \(M\) indicating the number of rows and columns. This is followed by \(N\) lines, each containing a string of length \(M\) representing the grid.
Output: For each test case, output a single integer that represents the number of distinct connected regions in the given grid.
inputFormat
The first line contains an integer \(T\), the number of test cases. For each test case:
- The first line contains two space-separated integers \(N\) and \(M\) indicating the grid's dimensions.
- The next \(N\) lines each contain a string of length \(M\), representing the grid.
All input is read from standard input (stdin).
outputFormat
For each test case, output a single integer on a new line representing the number of connected regions. All output should be written to standard output (stdout).
## sample2
4 5
RRRRR
RRGGG
RRRGG
GGGGG
2 3
BBB
BBB
2
1
</p>