Python 0959.py
class Solution:
def regionsBySlashes(self, grid: List[str]) -> int:
width = len(grid[0])
height = len(grid)
# each cell consists of four areas:
# \ 0 /
# \ /
# 1 X 2
# / \
# / 3 \
up = 0
left = 1
right = 2
down = 3
# unique integer code for each cell
def id(x, y, area):
return x * 1000 + y * 10 + area # 1 <= x,y <= 30 according to problem constraints
# union-find, copied from problem 721
parent = {}
# initially parent[a] = a
for y in range(height):
for x in range(width):
for area in range(4):
i = id(x, y, area)
parent[i] = i
def union(a, b):
a = find(a)
b = find(b)
if a == b:
return
if a < b:
parent[b] = a
else:
parent[a] = b
def find(a):
if parent[a] != a:
parent[a] = find(parent[a]) # path compression
return parent[a]
# merge two cells, check if x2/y2 is valid (x1/y2 is assumed to be valid)
def merge(x1, y1, area1, x2, y2, area2):
if 0 <= x2 < width and 0 <= y2 < height:
union(id(x1, y1, area1), id(x2, y2, area2))
for y in range(height):
for x in range(width):
cell = grid[y][x]
if cell == "/" or cell == " ":
merge(x, y, left, x - 1, y, right)
merge(x, y, up, x, y - 1, down)
merge(x, y, left, x, y, up)
merge(x, y, right, x + 1, y, left)
merge(x, y, down, x, y + 1, up)
merge(x, y, right, x, y, down)
if cell == "\\" or cell == " ":
merge(x, y, left, x - 1, y, right)
merge(x, y, down, x, y + 1, up)
merge(x, y, left, x, y, down)
merge(x, y, right, x + 1, y, left)
merge(x, y, up, x, y - 1, down)
merge(x, y, right, x, y, up)
unique = set()
for y in range(height):
for x in range(width):
unique.add(find(id(x, y, up)))
unique.add(find(id(x, y, left)))
unique.add(find(id(x, y, right)))
unique.add(find(id(x, y, down)))
return len(unique)
Difficulty
and has an acceptance rate of about 78% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Breadth First Search
- Depth First Search
- Hash Table
- Matrix
- Union Find
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation computes the number of distinct regions formed by slashes (/), backslashes (\), and spaces inside a square grid. It treats each cell as four triangular sub-areas and connects them using a union-find (disjoint-set) structure. By merging sub-areas that belong to the same physical region and finally counting the unique set representatives, the algorithm derives the total region count.
Data Representation
The grid dimensions are extracted first:
width = len(grid[0])
height = len(grid)
Each cell is conceptually divided into four parts, labelled up, left, right, and down. The integer constants are defined for readability:
up = 0
left = 1
right = 2
down = 3
A deterministic identifier for any sub-area is generated by the id function. The formula packs the cell coordinates and the area index into a single integer, guaranteeing uniqueness for the problem’s size limits (grid size ≤ 30 × 30):
def id(x, y, area):
return x * 1000 + y * 10 + area
Union-Find Initialization
A dictionary parent stores the parent pointer for each sub-area. Initially every identifier points to itself, establishing each sub-area as a separate set:
parent = {}
for y in range(height):
for x in range(width):
for area in range(4):
i = id(x, y, area)
parent[i] = i
The find routine implements path compression, flattening the tree structure on each lookup:
def find(a):
if parent[a] != a:
parent[a] = find(parent[a])
return parent[a]
The union routine merges two sets by linking the larger identifier to the smaller one, which keeps the tree shallow without requiring explicit rank tracking:
def union(a, b):
a = find(a)
b = find(b)
if a == b:
return
if a < b:
parent[b] = a
else:
parent[a] = b
Merge Helper
A small helper validates neighbor coordinates before invoking union. It assumes the source cell is always valid and only checks the target cell’s bounds:
def merge(x1, y1, area1, x2, y2, area2):
if 0 <= x2 < width and 0 <= y2 < height:
union(id(x1, y1, area1), id(x2, y2, area2))
Cell Processing Logic
The core loop iterates over every cell, examines its character, and performs a series of merge calls that encode the connectivity implied by the slash, backslash, or empty space.
When the character is a forward slash (/) or a space, the following connections are established:
if cell == "/" or cell == " ":
merge(x, y, left, x - 1, y, right)
merge(x, y, up, x, y - 1, down)
merge(x, y, left, x, y, up)
merge(x, y, right, x + 1, y, left)
merge(x, y, down, x, y + 1, up)
merge(x, y, right, x, y, down)
When the character is a backslash (\) or a space, a different set of connections is applied:
if cell == "\\" or cell == " ":
merge(x, y, left, x - 1, y, right)
merge(x, y, down, x, y + 1, up)
merge(x, y, left, x, y, down)
merge(x, y, right, x + 1, y, left)
merge(x, y, up, x, y - 1, down)
merge(x, y, right, x, y, up)
The inclusion of the space case in both branches ensures that an empty cell behaves as if it contains both a forward slash and a backslash, effectively merging all four sub-areas together.
Counting Distinct Regions
After all merges are performed, the algorithm walks the entire grid once more, invoking find on each sub-area and inserting the resulting root into a set. The cardinality of this set equals the number of distinct regions:
unique = set()
for y in range(height):
for x in range(width):
unique.add(find(id(x, y, up)))
unique.add(find(id(x, y, left)))
unique.add(find(id(x, y, right)))
unique.add(find(id(x, y, down)))
return len(unique)
Edge Cases Handled
The code gracefully handles cells located on the grid borders. The merge helper checks neighbor coordinates before attempting a union, preventing out-of-range accesses for cells on the top row, bottom row, leftmost column, or rightmost column. Consequently, regions that touch the outer boundary are correctly accounted for without special casing.
Empty cells (represented by a space) are treated as fully open areas. By executing both the forward-slash and backslash merge blocks for a space, all four sub-areas of that cell become mutually connected, which collapses any internal boundaries that would otherwise be introduced by slashes.
The identifier generation function uses a multiplier (1000) that comfortably exceeds the maximum possible x coordinate (30) and a secondary multiplier (10) that exceeds the maximum y coordinate (30). This guarantees that identifiers for distinct cells never collide, even when the area index varies.
Performance Optimizations
Path compression inside find reduces the depth of the union-find trees, ensuring that subsequent find operations run in near-constant time. The union implementation prefers the smaller identifier as the new root, which, while simple, often yields a balanced tree because identifiers are roughly ordered by their position in the grid.
The algorithm avoids constructing an explicit adjacency list; instead, it directly merges neighboring sub-areas during the single pass over the grid. This in-place merging eliminates the overhead of auxiliary data structures and keeps memory usage proportional to the number of sub-areas (four per cell).
By using a dictionary for parent rather than a list, the code sidesteps the need to pre-allocate a large contiguous array, which is advantageous given the sparse identifier space created by the id function. The final region count is obtained with a single set insertion per sub-area, avoiding repeated scans or additional passes.
ELI5 - Simplified Explanation
Imagine you have a big sheet of paper covered in square boxes. Inside each box, you can draw lines to split the space into smaller triangle-shaped rooms. Some lines go from the top left to the bottom right, and others go the opposite way.
To count how many separate rooms are hidden inside all those squares, you need to use a clever trick. Imagine every little triangle is its own tiny island. When two triangles touch each other and there is no wall separating them, they act like they belong to the same backyard. You want to group all these triangles together if they are connected.
The code works by giving every single triangle a special number so it can be tracked. It looks at every square in the grid one by one. If it sees a slash, it knows exactly which sides are blocked by that line and which sides are open. When the code sees an open side, it connects that triangle to the neighbor next to it by telling them they are part of the same island family.
After checking every square and linking up all the connected neighbors, you look at all the islands again. By counting up how many different group families exist, you find out exactly how many separate rooms were created by all the slashes. It is like finishing a big puzzle and counting all the distinct patches of color on the paper.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | |||||||
| leetcode.ca | C++ | JS | Java | Go | Python | TS | |||
| LeetcodeHelp | C++ | Java | Python | ||||||
| Progiez | C++ | Java | Python | ||||||
| github | BigEggStudy | C# | |||||||
| black-shadows | C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| FelixFan1122 | Java | ||||||||
| fsq | C++ | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| Shamik07 | Dart | ||||||||
| suxrobGM | C# | ||||||||
| wisdompeak | C++ | ||||||||
| withaarzoo | Go | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Java | ||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| BigEggStudy | C# | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| FelixFan1122 | Java | ||||||||
| fsq | C++ | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| Shamik07 | Dart | ||||||||
| suxrobGM | C# | ||||||||
| wisdompeak | C++ | ||||||||
| withaarzoo | Go |
Videos
Solved On The Same Day
- problem 953: Verifying an Alien Dictionary
- problem 961: N-Repeated Element in Size 2N Array
- problem 2264: Largest 3-Same-Digit Number in String
- problem 2682: Find the Losers of the Circular Game
- problem 2784: Check if Array is Good
- problem 2848: Points That Intersect With Cars
- problem 2869: Minimum Operations to Collect Elements
- problem 890: Find and Replace Pattern
- problem 954: Array of Doubled Pairs
- problem 966: Vowel Spellchecker
- problem 1202: Smallest String With Swaps
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality