#K95567. Cycle Detection in a Grid
Cycle Detection in a Grid
Cycle Detection in a Grid
You are given a grid of characters with n rows and m columns. Your task is to determine if there exists a cycle in the grid. A cycle is defined as a path consisting of at least four cells that starts and ends at the same cell, and all cells on the path (except the starting/ending cell) must be distinct. Moreover, every consecutive pair of cells in the path must be adjacent horizontally or vertically, and all cells in the cycle must contain the same character.
Note that a valid cycle must satisfy:
- The cycle length is at least 4 (i.e., it contains at least 4 cells).
- You cannot immediately backtrack to the previous cell; that is, the cell from which you just came does not count as a valid next step in forming a cycle.
Formally, if we denote the cycle path as a sequence of grid cells \( (x_1,y_1), (x_2,y_2), \dots, (x_k,y_k) \) with \( k \ge 4 \), then:
[ \begin{aligned} & \text{For all } 1 \leq i < k, ; (x_i,y_i) \text{ and } (x_{i+1},y_{i+1}) \text{ are adjacent, and } \ & (x_1,y_1) = (x_k,y_k), \quad \text{and} \quad {(x_1,y_1), (x_2,y_2), \dots, (x_{k-1},y_{k-1})} \text{ are all distinct.} \end{aligned} ]
If such a cycle exists, print Yes
; otherwise, print No
for that test case.
inputFormat
The first line of input contains an integer T representing 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 in the grid. This is followed by n lines with each line being a string of length m representing the grid rows.
Input is provided via stdin.
outputFormat
For each test case, output a single line containing either Yes
if there exists a cycle in the grid, or No
if no cycle exists. The answers for all test cases should be printed on separate lines via stdout.
1
3 3
aaa
aaa
aaa
Yes