#K65562. Longest Uniform Path in a Grid
Longest Uniform Path in a Grid
Longest Uniform Path in a Grid
You are given a grid of size \( n \times m \) each cell contains a lowercase English letter. Your task is to find the length of the longest connected path in the grid such that all cells along this path contain the same letter. Two cells are considered connected if they are adjacent vertically or horizontally.
In other words, for every connected component of identical letters in the grid, determine its size and output the maximum size among all such components.
Note: A cell is connected to its 4 adjacent cells (up, down, left, and right). The grid is processed for multiple test cases.
The solution requires reading the input from stdin
and writing the output to stdout
.
inputFormat
The first line of the input contains a single integer \( T \) denoting the number of test cases. For each test case, the first line contains two integers \( n \) and \( m \) representing the number of rows and columns of the grid, respectively. This is followed by \( n \) lines, each containing a string of length \( m \) which represents a row of the grid.
Example:
2 2 2 aa aa 3 3 aba bbb ccd
outputFormat
For each test case, output a single integer on a new line representing the length of the longest uniform path (i.e. the maximum size of any connected component of the same letter in the grid).
Example:
4 4## sample
7
2 2
aa
aa
3 3
aba
bbb
ccd
1 5
abcde
5 1
a
a
a
a
a
3 3
abc
bdb
ccc
4 4
abcd
efgh
ijkl
mnop
2 2
ab
ba
4
4
1
5
3
1
1
</p>