Problem 1091

Abstract / Summary

Find the shortest path between two cells in a binary matrix where you can move in 8 directions and can only step on zeros.

Note

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

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
36 lines | 1050 bytes | submitted October 2, 2023 | GitHub   11% comment ratio | tab size 4 | moderate complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 52% (1+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Breadth First Search
  • Matrix
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 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.

written by openai gpt

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.

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.78 | σ = 1.34

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 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
29 links | 18 authors | 8 languages

Videos

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

Solved On The Same Day

14 solutions   October 2, 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