Problem Description
Given an m x n grid of lowercase English letters, determine whether there exists a cycle in the grid that consists of the same character. A valid cycle is a path of length 4 or more that starts and ends at the same cell, moves only in four directions (up, down, left, right), and does not immediately reverse the last move.
Key Insights
- Use Depth First Search (DFS) to explore connected cells with the same character.
- Track the DFS path using a recursion “visited” (or recursion stack) to detect a cycle.
- Avoid considering the immediate parent cell in DFS to prevent trivial backtracking.
- Use a global visited array to avoid reprocessing nodes from previously explored components.
- A cycle is valid only if the path has a length of at least 4.
Space and Time Complexity
Time Complexity: O(m * n) – each cell is processed once. Space Complexity: O(m * n) – for global and recursion visited arrays in the worst-case scenario.
Solution
We solve the problem using DFS. For each cell that has not been globally visited, we perform a recursive DFS that follows adjacent cells with the same character. We maintain a separate 2D array to track cells in the current DFS call (recursion stack). During DFS, if we encounter a cell that is already in the current DFS path (and it isn’t the immediate parent) and the current path length is at least 4, we have found a cycle. After processing a component, we mark all cells visited in that DFS to skip redundant work later.