Shortest paths on grids, and 0-1 BFS
🌍 In real life. A hiking map is a grid of squares, and each square has a number: how tiring it is to cross (1 for a flat field, 9 for a swamp). The best walk from the top-left to the bottom-right is not the one with fewest squares but the one with the smallest total. A cleaning robot in an office faces a simpler version: moving along a corridor is free, and every door it must open costs 1, so it wants the route with the fewest doors.
The idea in one sentence: a grid is a graph, each square a place and each step to a neighbour an edge whose weight is the cost of the square you step onto, so Dijkstra works unchanged; and when every weight is just 0 or 1, a deque can replace the heap: free steps go to the front, steps that cost 1 go to the back.
Its words:
- neighbours: the squares up, down, left and right (inside the grid)
- 0-1 BFS: shortest paths when every weight is 0 or 1, using a deque instead of a heap
- deque: a queue you can add to at either end (
appendleft,append) in O(1)
Step by step, 0-1 BFS:
dist = {start: 0}anddq = deque([start])- take the place at the front
- for each neighbour: if
dist[v] + wbeats what it has, store it; then ifw == 0put it at the front, else at the back - repeat until the deque is empty
Watch it on a small map: roads marked 0 are free, roads marked 1 cost one. A place reached for free jumps the queue:
Why the deque stays in order. When you take a place at distance d from the front, its free neighbours get d (front) and its other neighbours get d + 1 (back). So the deque only ever holds distances d and d + 1, smaller ones in front: it is already sorted, exactly what the heap was for, without the heap's log. Like Dijkstra, a place can be added twice; the second, smaller entry comes out first, and the stale one only finds nothing to improve.
What it costs, by counting. A grid of R rows and C columns has R × C places and at most 4 × R × C steps. A 1,000 × 1,000 map has 1,000,000 squares and about 4,000,000 steps. Dijkstra pays a heap log for each, about 4,000,000 × 20 = 80,000,000 small steps; 0-1 BFS pays O(1) each: O(V + E), about 5,000,000. Plain BFS (Chapter 51) is the special case where every weight is 1.
import heapq
def grid_path_cost(grid):
rows, cols = len(grid), len(grid[0])
dist = {(0, 0): int(grid[0][0])} # you pay for the square you start on, too
heap, done = [(dist[(0, 0)], 0, 0)], set()
while heap:
d, r, c = heapq.heappop(heap)
if (r, c) in done:
continue
done.add((r, c))
if (r, c) == (rows - 1, cols - 1):
return d # settled: nothing can beat it now
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < rows and 0 <= nc < cols:
nd = d + int(grid[nr][nc]) # stepping onto a square costs its number
if (nr, nc) not in dist or nd < dist[(nr, nc)]:
dist[(nr, nc)] = nd
heapq.heappush(heap, (nd, nr, nc))
from collections import deque
def min_walls(grid):
rows, cols = len(grid), len(grid[0])
dist = {(0, 0): 0}
dq = deque([(0, 0)])
while dq:
r, c = dq.popleft()
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < rows and 0 <= nc < cols:
w = 1 if grid[nr][nc] == "#" else 0
nd = dist[(r, c)] + w
if (nr, nc) not in dist or nd < dist[(nr, nc)]:
dist[(nr, nc)] = nd
if w == 0:
dq.appendleft((nr, nc)) # free step: same distance, go first
else:
dq.append((nr, nc)) # costs 1: wait at the back
return dist[(rows - 1, cols - 1)]
print(grid_path_cost(["131", "151", "421"]))
print(min_walls([".#.", ".#.", "..."]))
print(min_walls([".#", "#."]))Mistakes and edge cases.
- only moving right and down: fine for some puzzles, but the cheapest walk may go up or left round a swamp; let all four neighbours in
- counting squares instead of cost: plain BFS finds the fewest steps, not the smallest total, once weights differ
- forgetting the start square: decide whether its own cost counts and stay consistent (here it does)
- 0-1 BFS with a weight of 2: the deque is no longer sorted; use Dijkstra
- putting free steps at the back: the deque is no longer in order, and a plain BFS that marks squares as seen the first time it meets them can keep a more expensive first visit
Quiz
In a grid where each square has a cost, what is the weight of the step from one square to its neighbour?
- The cost of the square you step onto
- Always 1
- The difference between the two squares
What does this print?
import heapq def grid_path_cost(grid): rows, cols = len(grid), len(grid[0]) dist = {(0, 0): int(grid[0][0])} # you pay for the square you start on, too heap, done = [(dist[(0, 0)], 0, 0)], set() while heap: d, r, c = heapq.heappop(heap) if (r, c) in done: continue done.add((r, c)) if (r, c) == (rows - 1, cols - 1): return d # settled: nothing can beat it now for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)): if 0 <= nr < rows and 0 <= nc < cols: nd = d + int(grid[nr][nc]) # stepping onto a square costs its number if (nr, nc) not in dist or nd < dist[(nr, nc)]: dist[(nr, nc)] = nd heapq.heappush(heap, (nd, nr, nc)) print(grid_path_cost(["19", "11"]))What does this print?
from collections import deque def min_walls(grid): rows, cols = len(grid), len(grid[0]) dist = {(0, 0): 0} dq = deque([(0, 0)]) while dq: r, c = dq.popleft() for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)): if 0 <= nr < rows and 0 <= nc < cols: w = 1 if grid[nr][nc] == "#" else 0 nd = dist[(r, c)] + w if (nr, nc) not in dist or nd < dist[(nr, nc)]: dist[(nr, nc)] = nd if w == 0: dq.appendleft((nr, nc)) # free step: same distance, go first else: dq.append((nr, nc)) # costs 1: wait at the back return dist[(rows - 1, cols - 1)] print(min_walls([".##.", "##..", "...#"]))Why may 0-1 BFS use a deque instead of a heap?
- The deque only ever holds two distances, d and d + 1, smaller ones in front, so it is already sorted
- A deque sorts itself
- Weights of 0 and 1 don't need the shortest path
With this, min_walls still finds the right count, but the deque falls out of order and squares are taken again and again. Which line is wrong?
def relax(dq, dist, here, there, w): nd = dist[here] + w if there not in dist or nd < dist[there]: dist[there] = nd if w == 0: dq.append(there) else: dq.append(there)
Coding tasks
A hiking map. Write
grid_path_cost(grid):gridis a list of equal-length strings of digits, each digit the cost of crossing that square. Return the smallest total cost of a walk from the top-left square to the bottom-right one, moving up, down, left or right, counting both end squares.Fewest walls. Write
min_walls(grid):gridis a list of strings of.(open) and#(wall), and the top-left square is open. Moving up, down, left or right, stepping onto a wall means breaking it, which costs 1. Return the fewest walls you must break to reach the bottom-right square.