Detect Cycles in 2D Grid Problem
Description
LeetCode Problem 1559.
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.
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
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 500gridconsists only of lowercase English letters.
Solution
Approach: BFS That Remembers the Parent
Treat the grid as a graph: each cell is a node, and two side-by-side cells with the same letter are joined by an edge. The question is whether this graph has a cycle. The grid graph is bipartite, so any cycle has length 4 or more automatically, and the "length 4 or more" rule needs no extra check.
Search each letter region with BFS, starting from every cell not yet visited. Along with each cell, keep the cell it was reached from (its parent). For each same-letter neighbor:
- If it is the parent, skip it: going straight back is not allowed, and that edge is the one we just used.
- If it is already visited, it was reached along a different route, so the two routes together close a cycle: return
true. - Otherwise mark it visited and add it to the queue.
If every region is searched without that happening, each region is a tree and the answer is false. An iterative BFS also avoids the deep recursion a DFS would need on a 500 x 500 grid of one letter.
Complexity: O(m * n) time and O(m * n) extra space.
from collections import deque
class Solution:
def containsCycle(self, grid: List[List[str]]) -> bool:
m, n = len(grid), len(grid[0])
visited = [[False] * n for _ in range(m)]
steps = ((1, 0), (-1, 0), (0, 1), (0, -1))
for si in range(m):
for sj in range(n):
if visited[si][sj]:
continue
# BFS over this letter's region, remembering the cell each cell was reached from.
visited[si][sj] = True
queue = deque([(si, sj, -1, -1)])
while queue:
i, j, pi, pj = queue.popleft()
for di, dj in steps:
x, y = i + di, j + dj
if not (0 <= x < m and 0 <= y < n) or grid[x][y] != grid[i][j]:
continue
if x == pi and y == pj:
continue # the edge we came along, not a cycle
if visited[x][y]:
return True # reached the same cell along a second route
visited[x][y] = True
queue.append((x, y, i, j))
return False