Problem 959

Abstract / Summary

Given a grid of slashes, count the number of separate regions formed by the cuts.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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)
78 lines | 2630 bytes | submitted December 4, 2023 | GitHub   21% comment ratio | tab size 4 | moderate complexity

Difficulty

This problem is ranked as
easy medium hard

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
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.93 | σ = 1.36

Complexity Analysis

Time: polynomial
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
32 links | 19 authors | 8 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

12 solutions   December 4, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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