#1559

Detect Cycles in 2D Grid

specialist · 830 · lc medium +31 · verified · 52.5% accepted · 1,324 likes · top 43%

Description

Given an m x n character grid grid, determine whether any cycle of length at least 4 exists where every cell on the cycle holds the same character. You may move to any of the four adjacent cells sharing the same character, but may not immediately backtrack to the cell just visited. Return true if such a cycle exists, false otherwise.

Example 1:

Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]]
Output: true
Explanation: There are two valid cycles shown in different colors in the image below:

Example 2:

Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]]
Output: true
Explanation: There is only one valid cycle highlighted in the image below:

Example 3:

Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]]
Output: false

Code

1
2
3