Approach
Depth-first search
For Regions Cut By Slashes, 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 Java from the credited upstream file 959.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 int regionsBySlashes(String[] grid) {3 final int n = grid.length;4 5 int[][] g = new int[n * 3][n * 3];6 7 for (int i = 0; i < n; ++i)8 for (int j = 0; j < n; ++j)9 if (grid[i].charAt(j) == '/') {10 g[i * 3][j * 3 + 2] = 1;11 g[i * 3 + 1][j * 3 + 1] = 1;12 g[i * 3 + 2][j * 3] = 1;13 } else if (grid[i].charAt(j) == '\\') {14 g[i * 3][j * 3] = 1;15 g[i * 3 + 1][j * 3 + 1] = 1;16 g[i * 3 + 2][j * 3 + 2] = 1;17 }18 19 int ans = 0;20 21 for (int i = 0; i < n * 3; ++i)22 for (int j = 0; j < n * 3; ++j)23 if (g[i][j] == 0) {24 dfs(g, i, j);25 ++ans;26 }27 28 return ans;29 }30 31 private void dfs(int[][] g, int i, int j) {32 if (i < 0 || i == g.length || j < 0 || j == g[0].length)33 return;34 if (g[i][j] != 0)35 return;36 37 g[i][j] = 2; 38 dfs(g, i + 1, j);39 dfs(g, i - 1, j);40 dfs(g, i, j + 1);41 dfs(g, i, j - 1);42 }43}44