Python 1391.py
class Solution:
def hasValidPath(self, grid: List[List[int]]) -> bool:
# union-find, copied from problem 721
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]
# convert 2D to 1D
def id(x, y):
return 1000 * x + y
# compatibility on the right side of a cell
horizontal = { 1: [ 1, 3, 5 ], 2: [], 3: [], 4: [ 1, 3, 5 ], 5: [], 6: [ 1, 3, 5 ] }
# compatibility on the bottom side of a cell
vertical = { 1: [ ], 2: [ 2, 5, 6 ], 3: [ 2, 5, 6 ], 4: [ 2, 5, 6 ], 5: [], 6: [] }
width = len(grid[0])
height = len(grid)
# identity
parent = {}
for y in range(height):
for x in range(width):
i = id(x, y)
parent[i] = i
# merge compatible streets
for y in range(height):
for x in range(width):
if x > 0:
left = grid[y][x - 1]
right = grid[y][x]
if right in horizontal[left]:
union(id(x - 1, y), id(x, y))
if y > 0:
up = grid[y - 1][x]
down = grid[y ][x]
if down in vertical[up]:
union(id(x, y - 1), id(x, y))
# is there a path ?
start = id(0, 0)
finish = id(width - 1, height - 1)
return find(start) == find(finish)
Difficulty
and has an acceptance rate of about 65% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Breadth First Search
- Depth First Search
- 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 determines whether a path exists from the top-left corner to the bottom-right corner of a rectangular grid where each cell contains a street type (1-6). The algorithm models the grid as a graph whose vertices are individual cells and whose edges represent compatible connections between neighboring cells. Connectivity is resolved using a union-find (disjoint-set) data structure with path compression, allowing the algorithm to answer the reachability question in essentially constant time after a single pass over the grid.
Union-Find Core
The union-find structure is defined by two nested functions, find and union. find retrieves the representative element of a set, applying path compression so that subsequent look-ups on the same element become direct references to the root. union merges two distinct sets by linking the larger representative to the smaller one, which reduces the height of the tree and improves future operations.
def find(a):
if parent[a] != a:
parent[a] = find(parent[a]) # path compression
return parent[a]
def union(a, b):
a = find(a)
b = find(b)
if a == b:
return
if a < b:
parent[b] = a
else:
parent[a] = b
The choice of the smaller identifier as the new root is a lightweight form of union by rank, avoiding the need for an auxiliary rank array while still keeping the trees shallow.
Mapping Two-Dimensional Coordinates to One Dimension
To store each cell in a flat dictionary, the code converts a pair of coordinates (x, y) into a unique integer identifier. The conversion multiplies the row index by a constant larger than any possible column count (1000) and adds the column index. This guarantees uniqueness for grids whose dimensions are below the constant, which holds for the problem constraints.
def id(x, y):
return 1000 * x + y
Because the identifier is deterministic and reversible, it can be used both for indexing the parent dictionary and for comparing the start and finish cells.
Compatibility Dictionaries
Two dictionaries, horizontal and vertical, encode which street types can connect to the right side and the bottom side of a cell, respectively. Each key is a street type, and the associated list enumerates the street types that are allowed to be adjacent on the specified side. By consulting these dictionaries, the algorithm decides whether two neighboring cells should belong to the same connected component.
horizontal = { 1: [1, 3, 5], 2: [], 3: [], 4: [1, 3, 5], 5: [], 6: [1, 3, 5] }
vertical = { 1: [], 2: [2, 5, 6], 3: [2, 5, 6], 4: [2, 5, 6], 5: [], 6: [] }
The empty lists represent street types that have no outgoing connection on that side, effectively preventing a union in those directions.
Parent Dictionary Initialization
Before any unions are performed, each cell is placed in its own singleton set. The code iterates over every row and column, computes the cell’s identifier, and stores it as its own parent. This step establishes the baseline disjoint-set structure.
parent = {}
for y in range(height):
for x in range(width):
i = id(x, y)
parent[i] = i
Because the dictionary is populated in a deterministic order, the identifiers are consistent across the entire execution.
Merging Compatible Cells
The main merging loop walks the grid a second time, examining each cell’s left and upper neighbors (if they exist). For a left neighbor, the algorithm checks whether the current cell’s type appears in the horizontal list of the left cell. For an upper neighbor, it checks whether the current cell’s type appears in the vertical list of the cell above. When a compatibility condition holds, the two cells are united in the disjoint-set structure.
for y in range(height):
for x in range(width):
if x > 0:
left = grid[y][x - 1]
right = grid[y][x]
if right in horizontal[left]:
union(id(x - 1, y), id(x, y))
if y > 0:
up = grid[y - 1][x]
down = grid[y][x]
if down in vertical[up]:
union(id(x, y - 1), id(x, y))
By only looking left and up, each pair of adjacent cells is considered exactly once, avoiding redundant union operations.
Final Connectivity Check
After all compatible unions have been performed, the algorithm determines whether the start cell (0, 0) and the finish cell (width-1, height-1) belong to the same set. If their representatives match, a valid path exists; otherwise, the grid is disconnected with respect to the street constraints.
start = id(0, 0)
finish = id(width - 1, height - 1)
return find(start) == find(finish)
Edge Cases Handled
The code gracefully handles grids where the start or finish cell contains a street type that lacks any outgoing connections. In such cases, the corresponding entry in the compatibility dictionaries is an empty list, preventing any union from being formed with neighboring cells. Consequently, the final find comparison correctly reports that no path exists.
Grids with a single cell are also covered. The initialization creates a singleton set for the only cell, and the final comparison checks the identifier against itself, yielding True when the cell’s type permits a trivial path (which is always the case because start and finish coincide).
When the grid dimensions are minimal (e.g., width or height equal to one), the merging loop skips the non-existent neighbor checks (x > 0 or y > 0), ensuring that no out-of-range accesses occur.
Performance Optimizations
The implementation leverages two classic union-find optimizations. Path compression in find flattens the tree structure on each lookup, guaranteeing that subsequent find calls on the same element are O(1). The union operation prefers the smaller identifier as the new root, which implicitly balances the tree without extra storage.
The algorithm processes the grid in two linear passes: one for initializing the parent map and another for merging compatible cells. Each cell is examined a constant number of times, and each union or find operation runs in near-constant amortized time due to the optimizations above. This results in an overall execution time that scales linearly with the number of cells, while memory usage is limited to the parent dictionary and the small compatibility dictionaries.
ELI5 - Simplified Explanation
Imagine a giant grid that looks like a city full of roads. Some road pieces go left and right, while others go up and down. This code is like a little map maker that checks if these road pieces are shaped correctly to touch each other.
First, it gives every single square in the city a special secret number so it can keep track of them. It uses a helpful trick called union-find that acts like a game of connecting dots. When two road pieces are next to each other and their patterns match up like puzzle pieces, the code draws an invisible line to join them together.
The code looks at the city one square at a time. It checks if the neighbor to the left fits with the current square and if the neighbor above fits with the current square. It uses two dictionaries filled with information about which road shapes are allowed to connect to which others.
After checking every square in the whole city, the code looks at the very first square where the journey starts and the final square at the end of the city. It asks if those two squares are part of the same connected group of roads. If the invisible lines have successfully linked the start to the finish, then a path exists.
Code Quality
Complexity Analysis
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++ | Java | Python | Go | |||
| Progiez | C++ | Java | Python | ||||
| github | black-shadows | C++ | |||||
| charles-wangkai | Java | ||||||
| fsq | C++ | ||||||
| JoshCrozier | JS | ||||||
| keineahnung2345 | C++ | ||||||
| lkwq007 | Python | ||||||
| lzl124631x | C++ | ||||||
| varunu28 | Java | ||||||
| withaarzoo | C++ | ||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||
| WalkCCC | C++, Java | ||||||
| leetcode.ca | C++, Go, Java, Python | ||||||
| Progiez | C++, Java, Python | ||||||
| black-shadows | C++, C++ | ||||||
| charles-wangkai | Java | ||||||
| fsq | C++ | ||||||
| JoshCrozier | JavaScript | ||||||
| keineahnung2345 | C++ | ||||||
| lkwq007 | Python | ||||||
| lzl124631x | C++ | ||||||
| varunu28 | Java | ||||||
| withaarzoo | C++ |
Videos
Solved On The Same Day
- problem 1403: Minimum Subsequence in Non-Increasing Order
- problem 1409: Queries on a Permutation With Key
- problem 1415: The k-th Lexicographical String of All Happy Strings of Length n
- problem 1471: The k Strongest Values in an Array
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