The Detect Cycles in 2D Grid coding problem asks you to find if there exists a cycle of length 4 or more in a 2D grid of characters. A cycle is defined as a path of the same character that starts and ends at the same cell, where each step moves to an adjacent cell (up, down, left, or right) and no cell is visited twice except for the starting cell.
Meta and Amazon ask this to test your proficiency with graph interview patterns applied to a grid. It evaluations your ability to adapt standard algorithms like DFS or Union Find to a 2D space. It also checks if you can handle the "parent" constraint (not moving back to the cell you just came from), which is the most critical part of cycle detection.
The most common approach is Depth-First Search (DFS).
Grid:
a a a
a b a
a a a
The 'a's form a square around the 'b'.
true.Cycle detection in grids is identical to cycle detection in undirected graphs. Remember the rule: "If you see a visited node that isn't your parent, you've found a cycle."
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Maximum Number of Fish in a Grid | Medium | Solve | |
| Number of Closed Islands | Medium | Solve | |
| Number of Enclaves | Medium | Solve | |
| Count Sub Islands | Medium | Solve | |
| Surrounded Regions | Medium | Solve |