Sub topic 13
0-1 BFS with a Double-Ended Queue
This chapter assumes you already know plain BFS with a FIFO queue, how BFS computes distances layer by layer, and how Python's collections.deque works. It also helps to know what Dijkstra's algorithm does, though you won't need its details.
Plain BFS finds shortest paths only when every edge costs the same. Some problems have two kinds of moves: free ones and ones that cost a single unit. Examples include flipping the fewest arrows in a grid, breaking the fewest walls, or switching transit lines the fewest times. For these graphs you don't need a priority queue. A double-ended queue, called a deque, is enough. This technique is called 0-1 BFS.
Why Plain BFS Breaks with 0-Weight Edges
Plain BFS assumes that a vertex discovered earlier is never farther away than one discovered later. Once edges can cost 0, that assumption fails. Consider this graph:
- A → B costs 1
- A → C costs 0
- C → B costs 0
Plain BFS from A marks B and C as visited in the same step, so it gives B a distance of 1 edge. The cheapest cost to reach B is actually 0, along A → C → B. Counting edges stops working once edges have different costs.
Dijkstra's algorithm gets this right, but it uses a binary heap, so each push or pop takes O(log V) time. With weights limited to 0 and 1, you can keep the vertices in distance order more cheaply.
The Core Idea
A 0-1 BFS keeps a deque of vertices waiting to be processed. When it relaxes an edge (u, v) with weight w, it does the following:
- If
dist[u] + wis smaller thandist[v], it updatesdist[v]. - If w is 0, v is just as close as u, so v goes to the front of the deque.
- If w is 1, v is one step farther, so v goes to the back.
The Invariant That Makes It Correct
At every moment, the distances stored in the deque take at most two values, d and d + 1. Every d entry sits in front of every d + 1 entry. Here is why that stays true:
- You pop u from the front, so
dist[u]is d, the smallest value in the deque. - A 0-edge gives v the distance d. Putting v at the front keeps the front section all d.
- A 1-edge gives v the distance d + 1. Putting v at the back keeps the back section all d + 1.
The deque therefore behaves like a priority queue with only two priority levels. That is all Dijkstra needs when weights are 0 or 1. Vertices come off the front in nondecreasing distance order, and the first time a vertex is popped, its distance is final.
The Implementation
from collections import deque
def zero_one_bfs(graph, start):
dist = {node: float('inf') for node in graph}
dist[start] = 0
dq = deque([start])
while dq:
u = dq.popleft()
for v, w in graph[u]:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
if w == 0:
dq.appendleft(v)
else:
dq.append(v)
return dist
graph = {
'A': [('B', 1), ('C', 0)],
'B': [('D', 0)],
'C': [('B', 0), ('D', 1)],
'D': [],
}
print(zero_one_bfs(graph, 'A')) # {'A': 0, 'B': 0, 'C': 0, 'D': 0}The adjacency list stores (neighbor, weight) pairs instead of bare neighbors. There is no visited set. The dist dictionary and the strict < comparison decide whether a vertex needs another look.
Tracing the Example
| Step | Popped (dist) | Updates | Deque after |
|---|---|---|---|
| start | none | dist[A] = 0 | [A] |
| 1 | A (0) | B = 1 to back, C = 0 to front | [C, B] |
| 2 | C (0) | B lowered to 0, to front; D = 1 to back | [B, B, D] |
| 3 | B (0) | D lowered to 0, to front | [D, B, D] |
| 4 | D (0) | no edges | [B, D] |
| 5 | B (0) | D is already 0, no change | [D] |
| 6 | D (0) | no edges | [] |
B and D each enter the deque twice. The second copies are stale entries: they are processed again, but they can't improve anything because the strict comparison fails.
How Many Times Can a Vertex Enter the Deque?
The first time v is relaxed from a vertex popped at distance d, v gets the distance d or d + 1. Every later pop has distance at least d, so v can never drop below d. If v started at d + 1, it can improve once, to d, and then never again. Each vertex is therefore inserted at most twice, and each edge is relaxed at most twice. The running time is O(V + E), the same as plain BFS, and the deque never holds more than 2V entries.
A Grid Application: Fewest Walls to Break
Grid problems often need 0-1 BFS. Suppose stepping into an open cell . is free and stepping into a wall # costs 1, because you have to break it. The question is how few walls you must break to get from the top-left cell to the bottom-right cell.
from collections import deque
def min_walls(grid, start, goal):
rows, cols = len(grid), len(grid[0])
INF = float('inf')
dist = [[INF] * cols for _ in range(rows)]
r0, c0 = start
dist[r0][c0] = 0
dq = deque([start])
while dq:
r, c = dq.popleft()
if (r, c) == goal:
return dist[r][c]
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols:
w = 1 if grid[nr][nc] == '#' else 0
if dist[r][c] + w < dist[nr][nc]:
dist[nr][nc] = dist[r][c] + w
if w == 0:
dq.appendleft((nr, nc))
else:
dq.append((nr, nc))
return -1
grid = ['.#..',
'.##.',
'##..']
print(min_walls(grid, (0, 0), (2, 3))) # 1The cost belongs to the cell you enter, so the weight is computed from grid[nr][nc]. Returning early at the goal is safe because of the invariant. The first time a cell leaves the front of the deque, its distance is final. This is the same reasoning that lets Dijkstra stop early. A stale copy of the goal can't be popped first, because the improved copy went to the front.
Common Mistakes
| Mistake | What goes wrong |
|---|---|
| Marking vertices visited on enqueue, as in plain BFS | A vertex first reached by a 1-edge can't be improved later through a 0-edge, so its distance comes out too high. |
| Pushing 0-weight neighbors to the back | The deque falls out of distance order, and pops no longer come in nondecreasing distance. The early exit also becomes wrong. |
| Using `<=` instead of `<` | Vertices with equal distances are pushed again and again, which wastes work. In graphs with 0-weight cycles, the pushes can repeat without end. |
| Storing the weight on the wrong end of a grid move | Charging for the cell you leave instead of the cell you enter shifts every answer by one wall. |
| Using it with weights other than 0 and 1 | The two-level invariant breaks. Use Dijkstra, or Dial's bucket algorithm for small integer weights. |
When to Reach for 0-1 BFS
| Algorithm | Edge weights | Time | Data structure |
|---|---|---|---|
| Plain BFS | all equal | O(V + E) | FIFO queue |
| 0-1 BFS | 0 or 1 | O(V + E) | deque, both ends |
| Dial's algorithm | integers 0..k | O(V·k + E) | array of buckets |
| Dijkstra | any nonnegative | O((V + E) log V) | binary heap |
Signs that a problem calls for 0-1 BFS:
- The problem asks for the minimum number of some special action, such as flips, breaks, or switches, while other moves are free.
- You can rewrite the state graph so that each transition either costs nothing or costs one unit.
- Plain BFS gives wrong answers because some moves are free.
You can also rescale. If every weight is 0 or c for one fixed c, divide by c, run 0-1 BFS, and multiply the result by c.
Exercise
Using the graph in this chapter (A→B weight 1, A→C weight 0, B→D weight 0, C→B weight 0, C→D weight 1), change the code so 0-weight neighbors are appended to the back instead of the front. Trace the first two pops. Which vertex is popped before its distance is final?
Show answer
After popping A, the deque is [B, C] with dist B = 1 and C = 0. B is popped next while dist[B] is still 1, even though its true distance is 0 through C. B's outgoing edges are relaxed using a wrong distance. The order of pops is no longer nondecreasing, so stopping early at a goal could return a wrong answer.
Exercise
Prove that in 0-1 BFS a vertex's distance can decrease at most once after it is first set.
Show answer
Suppose v is first relaxed from u, popped at distance d. Then dist[v] is d or d + 1. Pops come in nondecreasing distance, so every later relaxation of v comes from a vertex at distance at least d and proposes a value of at least d. If dist[v] = d, nothing can lower it. If dist[v] = d + 1, the only smaller possible value is d, so it can decrease once at most. Each vertex is therefore pushed at most twice.
Exercise
A graph has edges of weight 1 and 2 only. How can you find shortest distances in O(V + E) time without a heap?
Show answer
Replace each weight-2 edge u→v with two weight-1 edges u→x→v through a new intermediate vertex x. That adds at most E vertices and E edges. Every edge now has weight 1, so plain BFS on the new graph gives correct distances for the original vertices in O(V + E) time.