#K57022. Taco Cycle Detection

    ID: 30328 Type: Default 1000ms 256MiB

Taco Cycle Detection

Taco Cycle Detection

You are given a grid of characters with n rows and m columns. Your task is to determine whether there exists a cycle of the same character in the grid. Two cells are considered adjacent if they share a common side (up, down, left, or right).

A cycle is defined as a path of at least four cells, where all cells on the path contain the same character, and the first and the last cell in the path are adjacent. Note that when moving from one cell to another, you should not immediately return to the cell you came from.

Constraints:

  • 2 ≤ n, m ≤ 1000

If such a cycle exists, print YES; otherwise, print NO.

The cycle can start from any cell in the grid. Use depth-first search (DFS) or any efficient graph traversal technique to solve the problem.

inputFormat

The first line contains two integers, n and m, representing the number of rows and columns in the grid respectively. The following n lines each contain a string of length m representing the rows of the grid.

Example:

3 4
aaaa
abab
aaaa

outputFormat

Output a single line containing YES if there exists a cycle of the same character in the grid, otherwise output NO.

## sample
3 4
aaaa
abab
aaaa
YES

</p>