Skip to content

959. Regions Cut By Slashes 👍

  • Time: $O(n^2)$
  • Space: $O(n^2)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Solution {
 public:
  int regionsBySlashes(vector<string>& grid) {
    const int n = grid.size();
    // G := upscaled grid
    vector<vector<int>> g(n * 3, vector<int>(n * 3));

    for (int i = 0; i < n; ++i)
      for (int j = 0; j < n; ++j)
        if (grid[i][j] == '/') {
          g[i * 3][j * 3 + 2] = 1;
          g[i * 3 + 1][j * 3 + 1] = 1;
          g[i * 3 + 2][j * 3] = 1;
        } else if (grid[i][j] == '\\') {
          g[i * 3][j * 3] = 1;
          g[i * 3 + 1][j * 3 + 1] = 1;
          g[i * 3 + 2][j * 3 + 2] = 1;
        }

    int ans = 0;

    for (int i = 0; i < n * 3; ++i)
      for (int j = 0; j < n * 3; ++j)
        if (g[i][j] == 0) {
          dfs(g, i, j);
          ++ans;
        }

    return ans;
  }

 private:
  void dfs(vector<vector<int>>& g, int i, int j) {
    if (i < 0 || i == g.size() || j < 0 || j == g[0].size())
      return;
    if (g[i][j] != 0)
      return;

    g[i][j] = 2;  // Mark 2 as visited.
    dfs(g, i + 1, j);
    dfs(g, i - 1, j);
    dfs(g, i, j + 1);
    dfs(g, i, j - 1);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Solution {
  public int regionsBySlashes(String[] grid) {
    final int n = grid.length;
    // G := upscaled grid
    int[][] g = new int[n * 3][n * 3];

    for (int i = 0; i < n; ++i)
      for (int j = 0; j < n; ++j)
        if (grid[i].charAt(j) == '/') {
          g[i * 3][j * 3 + 2] = 1;
          g[i * 3 + 1][j * 3 + 1] = 1;
          g[i * 3 + 2][j * 3] = 1;
        } else if (grid[i].charAt(j) == '\\') {
          g[i * 3][j * 3] = 1;
          g[i * 3 + 1][j * 3 + 1] = 1;
          g[i * 3 + 2][j * 3 + 2] = 1;
        }

    int ans = 0;

    for (int i = 0; i < n * 3; ++i)
      for (int j = 0; j < n * 3; ++j)
        if (g[i][j] == 0) {
          dfs(g, i, j);
          ++ans;
        }

    return ans;
  }

  private void dfs(int[][] g, int i, int j) {
    if (i < 0 || i == g.length || j < 0 || j == g[0].length)
      return;
    if (g[i][j] != 0)
      return;

    g[i][j] = 2; // Mark 2 as visited.
    dfs(g, i + 1, j);
    dfs(g, i - 1, j);
    dfs(g, i, j + 1);
    dfs(g, i, j - 1);
  }
}