#959

Regions Cut By Slashes

Medium
ArrayHash TableDepth-First SearchBreadth-First SearchUnion-FindMatrixUnion-FindGraph Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n² * α(n))
Space
O(1)
O(n)
💡

Intuition

Time O(n² * α(n))Space O(n)

The optimal approach uses a union-find data structure to efficiently group connected regions. By treating each cell as a node, we can quickly unite regions based on the slashes and spaces.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a union-find structure to manage the regions.
  2. 2Step 2: Traverse each cell in the grid and determine connections based on the characters ('/', '\', ' ').
  3. 3Step 3: For each cell, union the appropriate neighboring cells based on the presence of slashes.
solution.py35 lines
1class UnionFind:
2    def __init__(self, n):
3        self.parent = list(range(n))
4        self.rank = [1] * n
5    def find(self, x):
6        if self.parent[x] != x:
7            self.parent[x] = self.find(self.parent[x])
8        return self.parent[x]
9    def union(self, x, y):
10        rootX = self.find(x)
11        rootY = self.find(y)
12        if rootX != rootY:
13            if self.rank[rootX] > self.rank[rootY]:
14                self.parent[rootY] = rootX
15            elif self.rank[rootX] < self.rank[rootY]:
16                self.parent[rootX] = rootY
17            else:
18                self.parent[rootY] = rootX
19                self.rank[rootX] += 1
20
21def regions_by_slashes(grid):
22    n = len(grid)
23    uf = UnionFind(n * n)
24    for i in range(n):
25        for j in range(n):
26            if grid[i][j] == ' ':
27                if i > 0: uf.union(i * n + j, (i - 1) * n + j)
28                if j > 0: uf.union(i * n + j, i * n + (j - 1))
29            elif grid[i][j] == '/':
30                if i > 0: uf.union(i * n + j, (i - 1) * n + (j + 1))
31                if j < n - 1: uf.union(i * n + j, i * n + (j + 1))
32            elif grid[i][j] == '\':
33                if i > 0: uf.union(i * n + j, (i - 1) * n + j)
34                if j > 0: uf.union(i * n + j, i * n + (j - 1))
35    return len(set(uf.find(x) for x in range(n * n)))

Complexity note: The time complexity is O(n² * α(n)), where α is the inverse Ackermann function, which grows very slowly, making it nearly constant for practical input sizes. The space complexity is O(n) for the union-find structure.

  • 1Understanding how slashes divide the grid is crucial.
  • 2Union-Find can efficiently manage connected components.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.