Python 1091.py
class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
if grid[0][0] == 1:
return -1
n = len(grid)
deltas = [ (-1, -1), (-1, 0), (-1, +1),
( 0, -1), ( 0, +1),
(+1, -1), (+1, 0), (+1, +1) ]
length = 1
have = set()
todo = set([( 0, 0 )])
while todo:
next = set()
for x, y in todo:
# done
if x == n - 1 and y == n - 1:
return length
# avoid loops
if (x, y) in have:
continue
have.add((x, y))
# all eight directions
for dx, dy in deltas:
xx = x + dx
yy = y + dy
if 0 <= xx < n and 0 <= yy < n and grid[yy][xx] == 0:
next.add(( xx, yy ))
length += 1
todo = next
return -1
Difficulty
and has an acceptance rate of about 52% (1+ million submissions).
Typical patterns to solve this problem:
- Array
- Breadth First Search
- Matrix
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 solves the “shortest path in a binary matrix” problem using a breadth-first search (BFS). It starts from the top-left cell, expands outward in all eight possible directions, and stops when the bottom-right cell is reached. The algorithm returns the length of the shortest clear path or -1 when no such path exists.
Initialization
The function begins by rejecting the trivial impossible case where the start cell is blocked:
if grid[0][0] == 1:
return -1
The size of the square matrix is stored in n. A list named deltas holds the eight directional offsets, allowing the neighbor generation code to stay compact. The BFS frontier is represented by a set todo that initially contains the start coordinate (0, 0). A separate set have records cells that have already been processed, preventing revisits. The variable length tracks the current path length, starting at 1 because the start cell itself counts as the first step.
n = len(grid)
deltas = [ (-1, -1), (-1, 0), (-1, +1),
( 0, -1), ( 0, +1),
(+1, -1), (+1, 0), (+1, +1) ]
length = 1
have = set()
todo = set([(0, 0)])
BFS Loop
The core of the algorithm is a while loop that continues as long as there are cells to explore in the current frontier:
while todo:
next = set()
for x, y in todo:
...
length += 1
todo = next
Inside the loop a new set next is prepared to collect the coordinates that will form the frontier for the following iteration. After processing all cells in todo, the path length is incremented and todo is replaced by next.
Neighbor Exploration
For each cell (x, y) taken from the current frontier, the algorithm first checks whether it is the target cell. If so, the current length is returned immediately:
if x == n - 1 and y == n - 1:
return length
The cell is then checked against the have set to avoid processing it more than once:
if (x, y) in have:
continue
have.add((x, y))
The eight possible moves are generated by iterating over deltas. For each direction the new coordinates (xx, yy) are computed, and a series of guards ensure that the move stays inside the matrix bounds and lands on a clear cell (0). Valid neighbors are added to the next set:
for dx, dy in deltas:
xx = x + dx
yy = y + dy
if 0 <= xx < n and 0 <= yy < n and grid[yy][xx] == 0:
next.add((xx, yy))
Termination Conditions
The loop terminates in two ways. The first is the early return when the target cell is reached, delivering the shortest path length. The second occurs when the frontier becomes empty, meaning no further expansion is possible. In that case the function falls through the loop and returns -1 to indicate that no clear path exists:
return -1
Edge Cases Handled
The code explicitly handles the situation where the starting cell is blocked, returning -1 without entering the BFS. It also correctly processes a single-cell matrix where the start is also the target; the early target check will succeed on the first iteration, returning a length of 1. Bounds checking (0 <= xx < n and 0 <= yy < n) prevents index errors when exploring neighbors at the matrix edges. The have set guarantees that cells are not revisited, which eliminates infinite loops that could arise from cycles in the graph representation of the matrix.
Performance Optimizations
Using a set for both the current frontier (todo) and the next frontier (next) provides O(1) average-time membership tests and insertions, which speeds up duplicate detection compared to a list-based approach. The pre-computed deltas list avoids recomputing direction vectors on each iteration. Early exit upon reaching the target avoids unnecessary exploration of remaining cells. The separation of visited cells (have) from the frontier ensures that each clear cell is processed at most once, limiting the total work to the number of reachable clear cells. The algorithm’s structure keeps memory usage proportional to the size of the frontier rather than the entire grid, which is advantageous for large sparse matrices.
ELI5 - Simplified Explanation
Imagine a giant square grid filled with little blocks, where some are blocked by walls and some are open paths. The game is to start at the very top left corner and find the fastest way to travel all the way to the bottom right corner. You can move in eight different directions, just like a king on a chessboard, stepping to any tile nearby that isn't a wall.
To solve this, the code acts like a scout sending out a team of explorers. First, it looks at the starting spot to see if a wall is already in the way. If the start is clear, it places the first explorer there. Then, for every step, the explorers reach out to all the empty tiles they can touch at the same time. Every time they take a group of steps, a counter goes up to keep track of how far they have traveled. It saves a list of every spot it has already visited so the explorers do not wander in circles. The group keeps spreading out in every open direction until the team finally lands on the bottom right corner. Once an explorer arrives there, the path is found.
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 | Python | C++ | Java | TS | ||||
| WalkCCC | C++ | Java | |||||||
| leetcode.ca | Python | C++ | Java | Go | Rust | TS | |||
| Progiez | Python | C++ | Java | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fpdjsns | C++ | ||||||||
| fsq | C++ | ||||||||
| Garvit244 | Python | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| vthwang | Java | ||||||||
| YuriSpiridonov | Python | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fpdjsns | C++ | ||||||||
| fsq | C++ | ||||||||
| Garvit244 | Python | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| vthwang | Java | ||||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 997: Find the Town Judge
- problem 695: Max Area of Island
- problem 797: All Paths From Source to Target
- problem 802: Find Eventual Safe States
- problem 863: All Nodes Distance K in Binary Tree
- problem 934: Shortest Bridge
- problem 1020: Number of Enclaves
- problem 1129: Shortest Path with Alternating Colors
- problem 1306: Jump Game III
- problem 1376: Time Needed to Inform All Employees
- problem 1557: Minimum Number of Vertices to Reach All Nodes
- problem 2038: Remove Colored Pieces if Both Neighbors are the Same Color
- problem 212: Word Search II
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