#1559

Detect Cycles in 2D Grid

Medium
ArrayDepth-First SearchBreadth-First SearchUnion-FindMatrixDepth-First Search (DFS)Graph Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(m * n)
O(m * n)
Space
O(m * n)
O(m * n)
💡

Intuition

Time O(m * n)Space O(m * n)

The optimal solution uses a modified DFS approach that tracks the previous cell to avoid immediate backtracking. This ensures we only explore valid paths and can efficiently detect cycles without redundant checks.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a visited set to keep track of visited cells.
  2. 2Step 2: For each cell in the grid, if it hasn't been visited, start a DFS.
  3. 3Step 3: In the DFS, check all four possible directions, ensuring not to revisit the immediate predecessor.
  4. 4Step 4: If we revisit a cell already in the current path (not the last cell), a cycle is detected.
  5. 5Step 5: Return true if any cycle is found; otherwise, return false after all cells are processed.
solution.py24 lines
1# Full working Python code
2from typing import List
3
4def hasCycle(grid: List[List[str]]) -> bool:
5    m, n = len(grid), len(grid[0])
6    visited = set()
7
8    def dfs(x, y, px, py, value):
9        if (x, y) in visited:
10            return True
11        visited.add((x, y))
12        for dx, dy in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
13            nx, ny = x + dx, y + dy
14            if 0 <= nx < m and 0 <= ny < n and grid[nx][ny] == value:
15                if (nx, ny) != (px, py) and dfs(nx, ny, x, y, value):
16                    return True
17        return False
18
19    for i in range(m):
20        for j in range(n):
21            if (i, j) not in visited:
22                if dfs(i, j, -1, -1, grid[i][j]):
23                    return True
24    return False

Complexity note: The time complexity remains O(m * n) as we still visit each cell once, but we avoid unnecessary revisits. The space complexity is O(m * n) due to the visited set.

  • 1Tracking the previous cell is crucial to avoid false cycles.
  • 2Using a visited set helps in efficiently managing state across recursive calls.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.