Debugging challengeIntermediate

BFS that blows up the queue

Scenario

A grid path finder works on small mazes but on a 1000×1000 open grid it runs for minutes and the queue grows to millions of entries. Distances are still correct on the small tests. Diagnose it.

Broken
1from collections import deque
2
3def shortest_path(grid, start, goal):
4 rows, cols = len(grid), len(grid[0])
5 q = deque([(start, 0)])
6 visited = set()
7
8 while q:
9 (r, c), d = q.popleft()
10 if (r, c) in visited:
11 continue
12 visited.add((r, c))
13 if (r, c) == goal:
14 return d
15 for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
16 nr, nc = r + dr, c + dc
17 if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 0:
18 q.append(((nr, nc), d + 1))
19 return -1

The corrected version appears here once you have revealed everything below.

Your task

  1. Explain why the returned distances are correct even though performance is terrible.
  2. Identify the line that lets the queue grow beyond O(V) and give an upper bound on how big it can get.
  3. Fix it and explain what invariant the fix restores.
  4. Discuss whether the same mistake in a *weighted* setting (Dijkstra) is acceptable.
DebuggingComplexity AnalysisEdge Cases

Work it out

Write your analysis before revealing anything. The self-check below compares it against what a strong answer contains.

Reveal

Progressive — each section builds on the previous one.

The bug
Why it happens
The fix
Edge cases
Complexity
What this tests

Self-check

Tick what your analysis covered. Be honest — this feeds your readiness profile.

0/7

Related concepts