Shortest path in a maze

Lesson 6.5 · Medium · BFS on a grid · 10 min · by Vinay C

We'll cover the following

Find the fewest steps from the top-left to the bottom-right of a grid, moving up, down, left or right. # is a wall.

Watch it run

Press Play or Step to walk through the example, or change the input and press Run. Each frame says what the algorithm does and why.

7 × 7 grid · 47 steps
0·#····
·······
······#
····#··
·······
·······
·······

Start at the top-left with distance 0. Goal is the bottom-right. # is a wall.

queue 1

1 / 47

The idea

Complexity

TimeSpaceWhy
O(R × C)O(R × C)Each open cell enters the queue at most once.

In Python

from collections import deque
def shortest(grid):
    R, C = len(grid), len(grid[0])
    q, dist = deque([(0, 0)]), {(0, 0): 0}
    while q:
        r, c = q.popleft()
        if (r, c) == (R - 1, C - 1): return dist[(r, c)]
        for dr, dc in ((1,0),(0,1),(-1,0),(0,-1)):
            nr, nc = r + dr, c + dc
            if 0 <= nr < R and 0 <= nc < C and grid[nr][nc] != '#' and (nr, nc) not in dist:
                dist[(nr, nc)] = dist[(r, c)] + 1
                q.append((nr, nc))
    return -1

Summary: say it in the interview

  • When every step costs the same, BFS spreads out like a ripple, so the first time it reaches the goal is the shortest route. Store each cell's distance as you add it to the queue.
  • Time O(R × C), space O(R × C). Each open cell enters the queue at most once.