Approach
Depth-first search
For Detect Cycles in 2D Grid, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 44 lines of C++ from the credited upstream file 1559.cpp.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 bool containsCycle(vector<vector<char>>& grid) {4 const int m = grid.size();5 const int n = grid[0].size();6 vector<vector<bool>> seen(m, vector<bool>(n));7 8 for (int i = 0; i < m; ++i)9 for (int j = 0; j < n; ++j) {10 if (seen[i][j])11 continue;12 if (dfs(grid, i, j, -1, -1, grid[i][j], seen))13 return true;14 }15 16 return false;17 }18 19 private:20 static constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};21 22 bool dfs(const vector<vector<char>>& grid, int i, int j, int prevI, int prevJ,23 char c, vector<vector<bool>>& seen) {24 seen[i][j] = true;25 26 for (const auto& [dx, dy] : kDirs) {27 const int x = i + dx;28 const int y = j + dy;29 if (x < 0 || x == grid.size() || y < 0 || y == grid[0].size())30 continue;31 if (x == prevI && y == prevJ)32 continue;33 if (grid[x][y] != c)34 continue;35 if (seen[x][y])36 return true;37 if (dfs(grid, x, y, i, j, c, seen))38 return true;39 }40 41 return false;42 }43};44