Shortest Path in Binary Matrix

MediumBreadth-first searchLeetCode 1091 ↗World 6-6
0:00 / 0:00

Cross a grid of open and blocked cells from top-left to bottom-right, moving in eight directions. Breadth-first search spreads out one ring at a time, so the first time it reaches the corner is the shortest path: O(n²).

▼

The problem

LeetCode 1091 (Medium). Given an n × n binary matrix grid, return the length of the shortest clear path from the top-left cell to the bottom-right cell, or −1 if there is none. A clear path visits only 0 cells, moves between cells that share an edge or a corner (eight directions), and its length is the number of cells it visits, both ends included (so a blocked start or goal means −1).

Examples (LeetCode's): [[0,1],[1,0]] → 2 (one diagonal step); [[0,0,0],[1,1,0],[1,1,0]] → 4 (right, diagonal down, down; also the run beside the code in scene 6); [[1,0,0],[1,1,0],[1,1,0]] → -1 (the start is blocked).

TRY IT ON LEETCODE ▶

The solution

def shortestPathBinaryMatrix(grid):
    n = len(grid)
    if grid[0][0] or grid[n - 1][n - 1]:
        return -1
    q = deque([(0, 0, 1)])
    seen = {(0, 0)}
    while q:
        r, c, d = q.popleft()
        if r == n - 1 and c == n - 1:
            return d
        for nr in range(r - 1, r + 2):
            for nc in range(c - 1, c + 2):
                if 0 <= nr < n and 0 <= nc < n:
                    if not grid[nr][nc] and (nr, nc) not in seen:
                        seen.add((nr, nc))
                        q.append((nr, nc, d + 1))
    return -1

Transcript

Shortest Path in Binary Matrix. In an n by n grid, zeros are open and ones are blocked. Go from the top-left to the bottom-right, stepping to any of eight neighbors, diagonals too. Return the shortest path length in cells, or minus one if none.

In zero one, one zero, one diagonal step works: two cells. In this three by three grid, go right, cut diagonally down, then down: four cells. If the start is blocked, it's minus one.

Depth-first search could try every path. On this five by five grid, its first path wanders down the left and takes nine cells. To be sure, it must compare all forty-eight paths, and bigger grids have exponentially more.

Breadth-first search explores in rings instead. The start is distance one, its open neighbors two, their new neighbors three. A queue keeps the order, first in, first out, so each ring finishes before the next. The first time the goal leaves the queue, its distance is the shortest.

One catch: mark a cell seen when you queue it, not when you pop it. Otherwise its neighbors queue it again and again. On an open five by five, that's seventy-three entries instead of twenty-five.

In code: if either corner is blocked, return minus one. Queue the start at distance one, marked seen. Pop from the front; if it's the goal, return its distance. Otherwise queue each open, unseen neighbor at distance plus one, marking it. If the queue empties, return minus one.

Back to the five by five. One at the corner. Two right and below. Three along the top and down the left. Four, then five slips through the gap. Six reaches the goal: when it leaves the queue, the answer is six. The top-right pocket never mattered.

Each cell is queued at most once and checks eight neighbors: O of n squared time. The queue and seen marks hold up to n squared cells: O of n squared space.

Spread ring by ring, mark cells as you queue them, stop at the goal. That's Shortest Path in Binary Matrix.