Regions Cut by Slashes

Count regions cut by slashes in an `n x n` grid by subdividing each cell into 4 triangles.

Medium
Time O(N^2 * α) Space O(N^2)
LeetCode
8 min read
union-find grid

Problem#

A grid of strings contains ' ', '/', and '\\'. Each character is a cell of an n x n grid; slashes split cells into pieces. Return the total number of distinct regions formed.

Examples#

  • [" /","/ "]2.
  • [" /"," "]1.
  • ["\\/","/\\"]5.

Constraints#

  • 1 <= n <= 30.

Hints#

Hint
Split each cell into 4 triangles (top, right, bottom, left). Union triangles within a cell based on the character; union across neighboring cells on shared edges.

Approach#

Each cell (r, c) becomes 4 DSU nodes: T, R, B, L. Indexed as (r * n + c) * 4 + k. Within a cell: ' ' unions all four; '/' unions T with L, B with R; '\\' unions T with R, B with L. Across cells: B of (r, c) with T of (r+1, c); R of (r, c) with L of (r, c+1). Count distinct roots.

Solution#

Regions Cut by Slashes
class Solution {
vector<int> parent;
int find(int x) { while (parent[x] != x) { parent[x] = parent[parent[x]]; x = parent[x]; } return x; }
void unite(int a, int b) { parent[find(a)] = find(b); }
public:
int regionsBySlashes(vector<string>& grid) {
int n = grid.size();
parent.resize(4 * n * n);
iota(parent.begin(), parent.end(), 0);
auto id = [&](int r, int c, int k) { return (r * n + c) * 4 + k; };
// k: 0=T, 1=R, 2=B, 3=L
for (int r = 0; r < n; ++r) {
for (int c = 0; c < n; ++c) {
char ch = grid[r][c];
if (ch == ' ') {
unite(id(r,c,0), id(r,c,1));
unite(id(r,c,1), id(r,c,2));
unite(id(r,c,2), id(r,c,3));
} else if (ch == '/') {
unite(id(r,c,0), id(r,c,3));
unite(id(r,c,1), id(r,c,2));
} else { // '\\'
unite(id(r,c,0), id(r,c,1));
unite(id(r,c,2), id(r,c,3));
}
if (r + 1 < n) unite(id(r,c,2), id(r+1,c,0));
if (c + 1 < n) unite(id(r,c,1), id(r,c+1,3));
}
}
unordered_set<int> roots;
for (int i = 0; i < (int)parent.size(); ++i) roots.insert(find(i));
return roots.size();
}
};

Editorial#

Subdividing each cell into 4 triangles is the canonical trick — slashes can be modeled exactly by which adjacent triangles they connect. The unions across cells respect grid adjacency. After all unions, distinct DSU roots correspond exactly to distinct regions.

Complexity#

  • Time: O(N^2 * α).
  • Space: O(N^2).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.