DSA Factory
Free Graphs lessonsGraphs · Stage 3 · Grids as graphs · Step 3

Shortest way through a maze

Use the ripple search on a grid of open cells and walls to find the fewest steps from corner to corner. About 14 minutes.

Cells in the line

The search is the one you know, with cells as the places. The line holds cells, each written as a row and column pair. Take a cell from the front, look at the four cells around it, and for each one that is on the map, open, and not yet reached, write its distance and add it to the back.

A wall is a cell you can never enter. A cell that is already reached is skipped. Those two checks are the whole difference between a maze and a plain graph.

Four looks: per cell: up, down, left, right.
Skip: walls, off-map cells and cells already reached.
In code
dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
for dr, dc in dirs:
    nr, nc = r + dr, c + dc
0 is open, 1 is a wall. Steps from the top-left to the bottom-right (distances fill in).
012
0
0
0
1
1
1
0
0
2
0
1
0
queue
[(0,0)]

Start at the top-left with distance 0. The walls are the cells holding 1.

Move 1 of 5

Check the corners first

A maze can be impossible in two quick ways. The start cell may itself be a wall, or the exit may be one. Both give an answer of -1 before you search at all.

Otherwise run the search until the line is empty. If the exit still has -1 written on it, no chain of open cells links the corners, and -1 is the right answer too. Notice there's no need for a special case for "no path". The search simply never reached it.

Walls at the ends: mean there is no way through.
Still -1: after the search means no route.
Quick check

In a maze where the start cell is itself a wall, what is the fewest number of steps?

  1. A-1, because you cannot stand on a wall
  2. B0, because you haven't moved yet
  3. C1, you step off the wall
Show the answer

-1, because you cannot stand on a wall. With no legal starting cell there is no route at all.

Your problem

Fewest steps through the maze

maze is a grid where 0 is an open cell and 1 is a wall. You start at the top-left cell and want to reach the bottom-right cell, moving one step at a time up, down, left or right through open cells. Return the fewest steps needed, or -1 if it is impossible. When the grid has a single open cell, the answer is 0.

Example
maze = [[0, 0, 1], [1, 0, 0], [0, 1, 0]] → 4

1 ≤ rows, columns ≤ 20 · each cell is 0 or 1

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve