Approach
Depth-first search
For Surrounded Regions, 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
- 35 lines of Java from the credited upstream file 130-2.java.
- The implementation visibly relies on sequence storage.
- 4 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 void solve(char[][] board) {3 if (board.length == 0)4 return;5 6 final int m = board.length;7 final int n = board[0].length;8 9 for (int i = 0; i < m; ++i)10 for (int j = 0; j < n; ++j)11 if (i * j == 0 || i == m - 1 || j == n - 1)12 dfs(board, i, j);13 14 for (char[] row : board)15 for (int i = 0; i < row.length; ++i)16 if (row[i] == '*')17 row[i] = 'O';18 else if (row[i] == 'O')19 row[i] = 'X';20 }21 22 23 private void dfs(char[][] board, int i, int j) {24 if (i < 0 || i == board.length || j < 0 || j == board[0].length)25 return;26 if (board[i][j] != 'O')27 return;28 board[i][j] = '*';29 dfs(board, i + 1, j);30 dfs(board, i - 1, j);31 dfs(board, i, j + 1);32 dfs(board, i, j - 1);33 }34}35