Sub topic 13
0-1 BFS with a Double-Ended Queue
This chapter assumes you know how plain BFS computes shortest distances in unweighted graphs and that you have used Python's collections.deque. Here we extend BFS to graphs where every edge costs either 0 or 1.
Why Plain BFS Breaks
Plain BFS treats every edge as one step. That works because the queue always holds vertices at distance d followed by vertices at distance d + 1, so vertices come out in order of distance. A 0-weight edge breaks that order. A neighbor reached through a 0-weight edge has the same distance as the current vertex, so it belongs with the distance-d group at the front. If you append it to the back, it waits behind vertices at distance d + 1, and BFS can settle some of those before it.
Dijkstra's algorithm would handle the weights correctly, but its priority queue costs O(log V) per operation. A double-ended queue (deque) supports O(1) pushes and pops at both ends, and that is enough when the only weights are 0 and 1.
The Rule
When you relax an edge u → v with weight w and the distance to v gets shorter:
- If
w == 0, pushvto the front. It has the same distance asu. - If
w == 1, pushvto the back. Its distance is one more thanu's.
With this rule, the deque always holds a run of vertices at distance d followed by a run at distance d + 1. That is the same two-layer order plain BFS relies on, so the vertex at the front always has the smallest tentative distance, just as it would in Dijkstra's algorithm.
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}Trace the start of the run. Popping A gives B a tentative distance of 1 (pushed to the back) and C a distance of 0 (pushed to the front). Popping C then lowers B to 0 through the free edge C → B. Plain BFS would have reported 1 for B.
Differences from Plain BFS
| Aspect | Plain BFS | 0-1 BFS |
|---|---|---|
| Visited check | Mark when enqueued; never revisit | Compare distances; a vertex may be pushed again |
| Edge weights | All 1 | 0 or 1 |
| Pushes per vertex | At most 1 | At most 2 |
| Time | O(V + E) | O(V + E) |
A vertex can be pushed twice: first to the back at distance d + 1, then to the front at distance d after a 0-weight edge improves it. Once a vertex gets the current minimum distance d, nothing can lower it again. So the total work stays linear.
Where 0-1 Weights Show Up
- Grids where moving in a preset direction is free and changing direction costs 1.
- Counting the fewest walls to break: stepping into an open cell costs 0, stepping into a wall costs 1.
- Graphs where you minimize the number of reversed edges: original edges cost 0, reversed edges cost 1.
Exercise
In zeroonebfs, suppose you change the code so that 0-weight neighbors are also pushed with append instead of appendleft. Run it on the example graph. Is the output still correct, and is the algorithm still correct in general?
Show answer
On this small graph, the output happens to still be correct, because the distance check lets B and D be improved and pushed again. In general, though, the deque loses its order: vertices at distance d can sit behind vertices at distance d + 1. Vertices then get popped and expanded with distances that are not yet final, which causes repeated re-relaxation. In the worst case the work grows far beyond O(V + E), and the algorithm stops behaving like Dijkstra. appendleft is what keeps 0-1 BFS both correct and linear.
Exercise
A graph has edge weights 0, 1, and 2. How can you still use 0-1 BFS?
Show answer
Replace each weight-2 edge u → v with two weight-1 edges through a new intermediate vertex: u → x → v. This adds at most one vertex and one edge per weight-2 edge, so the run stays linear in the size of the original graph. The other option is Dijkstra's algorithm.