← Practice
πŸ“– BFS and DFSbfs-shortest-path-grid
LessonΒ·difficulty 5/5Β·~25 min

BFS: shortest path in a grid

BFS: shortest path in a grid

Given a grid where 0 is open and 1 is a wall, find the shortest path from the top-left corner (0, 0) to the bottom-right corner (n-1, m-1), moving only up/down/left/right through open cells.

Breadth-first search is the right tool: it explores the grid in rings of increasing distance, so the first time it reaches the destination it has found a shortest route. We push the start cell into a queue, then repeatedly pop a cell and push its unvisited open neighbours, carrying along the distance so far.

python
queue = deque([(0, 0, 1)])   # (row, col, cells_visited_so_far)
seen  = {(0, 0)}
while queue:
    r, c, dist = queue.popleft()
    if (r, c) is the destination: return dist
    ... push open, unseen neighbours with dist + 1 ...

We count cells visited on the path (so a 1x1 open grid has answer 1).

Your task

Write shortest_path(grid) returning the number of cells on the shortest path from top-left to bottom-right, or -1 if there is no path (including when the start or end cell is itself a wall).

python
shortest_path([[0, 0, 0], [1, 1, 0], [0, 0, 0]])  # 5
shortest_path([[0, 1], [1, 0]])                     # -1
shortest_path([[0]])                                # 1

Hint: use collections.deque for the queue and a seen set of (row, col). Check the start/end-wall cases up front before you start the search.

Tests

  • zigzag path
  • blocked
  • single cell
  • straight row
  • long detour (hidden)
  • start is a wall (hidden)

✦ Stuck? Ask for a spark

warming up
Loading editor…

$ Console output will appear here.

>_AI tutor
Sign in to chat with the tutor.