Algorithms · Level 2 Graphs

Shortest Path with BFS

Find the fewest steps from a start to a goal through a warehouse map with breadth-first search, which explores in rings so the first arrival is the shortest.

  • explore in rings with a queue
  • the first arrival is the shortest
  • mark cells as seen when you queue them

Breadth-first search explores in rings: every cell 1 step away, then 2, then 3. The first time it reaches the goal is the shortest path. Trap: mark a cell as seen when you queue it; marking it when you pop it lets the same cell be queued many times.

from collections import deque
queue, seen = deque([start]), {start}
while queue:
    cell = queue.popleft()
    for nxt in neighbours(cell):
        if nxt not in seen:
            seen.add(nxt)
            queue.append(nxt)

Write shortest_path(grid): grid is a list of strings with S (start), E (end), # (shelf) and . (aisle). Return the fewest up, down, left or right steps from S to E, or -1 if E can't be reached. Example: shortest_path(['S.#', '..E']) → 3.

solution.py
Test Suites Pending
Output