Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid.

A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell.

Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell.

Return true if any cycle of the same value exists in grid, otherwise, return false.

Input & Output

Example 1 — Basic Cycle
$ Input: grid = [["a","b","b"],["a","a","b"],["a","a","a"]]
Output: true
💡 Note: There is a cycle with same value 'a': (0,0) → (1,0) → (1,1) → (2,1) → (2,2) → (2,0) → back to (0,0)
Example 2 — No Cycle
$ Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]]
Output: false
💡 Note: No cycles exist in this grid. Each connected component of same characters forms a tree structure
Example 3 — Small Cycle
$ Input: grid = [["a","a"],["a","a"]]
Output: true
💡 Note: Simple 2x2 square forms a cycle: (0,0) → (0,1) → (1,1) → (1,0) → back to (0,0)

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 ≤ m, n ≤ 500
  • grid consists only of lowercase English letters

Visualization

Tap to expand
INPUT GRIDDFS ALGORITHMRESULTabbaabaaa3x3 grid with charactersFind cycles of same values1Start DFS from unvisited cells2Mark visited, explore 4 directions3Skip parent cell4If visited cell found → Cycle!trueCycle DetectedPath forms cycle:(0,0)→(1,0)→(1,1)→(2,1)→(2,2)→(2,0)→(0,0)Key Insight:A cycle exists when DFS reaches a previously visited cell that is not the immediate parent.This happens because we can only reach the same cell through a different path, forming a loop.TutorialsPoint - Detect Cycles in 2D Grid | DFS with Parent Tracking
Asked in
Google 42 Amazon 38 Meta 31 Microsoft 29
34.5K Views
Medium-High Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen