How 0-1 BFS uses a deque for weights zero and one

Short answer: 0-1 BFS computes shortest paths when every edge weight is 0 or 1. A relaxation of weight 0 pushes the neighbor at the front of a deque, and a relaxation of weight 1 pushes it at the back. The front of the deque stays in distance order, so each vertex is settled in linear time, O(V+E). It is Dijkstra for this weight set, with the heap replaced by the two ends of a deque.


What the problem actually asks

A binary heap spends a logarithm to find the next smallest tentative distance. If an edge can increase the distance by only 0 or 1, the frontier never contains a gap wider than 1. Vertices at the current distance belong in front of vertices at the current distance plus one. A deque expresses exactly those two buckets.

Pushing a zero-weight improvement to the front keeps it with the current distance. Pushing a one-weight improvement to the back schedules it after every vertex that is already one closer. No other weight is allowed to use either end.


What the algorithm guarantees

On a graph whose weights are only 0 and 1, the algorithm returns true shortest paths and runs in O(V+E), because each vertex is enqueued a constant number of times when a settled vertex is not reprocessed. Extra memory is the deque and the distance array. The same proof as Dijkstra applies: the front vertex has the minimum tentative distance.

A weight of 2 or more, pushed as if it were 1, lands in the wrong bucket and can be settled too early. Dial’s algorithm is the generalization that keeps a bucket per integer residue when weights are small integers up to C. Ordinary BFS is the special case in which every weight is 1, so the front push never happens and a queue suffices.


The working steps

  1. Set dist[source] = 0 and every other distance to infinity. Push the source on a deque.
  2. Pop u from the front. If u was already settled at a better distance, skip it.
  3. For an edge u→v of weight w in {0, 1}, if dist[u]+w < dist[v], update dist[v] and parent[v].
  4. If w = 0, push v at the front. If w = 1, push v at the back.
  5. Continue until the deque is empty. The parent pointers are a shortest-path tree.

The linear bound is for weights in {0, 1}. Arbitrary nonnegative weights need a heap. Small integer weights up to a bound C need Dial’s buckets. Negative weights need Bellman-Ford. Treating a general graph as 0-1 by clamping weights produces distances for a different graph.


Approaches that look simpler and fail

Approach Why it fails when a weight is neither zero nor one
Push every improved neighbor to the back A zero-weight edge then waits behind vertices that are farther away. The pop order is no longer distance order unless every weight is 1.
Push a weight-2 edge to the back as though it cost 1 The neighbor’s true distance is not the current distance plus one. Later pops can be wrong.
Use the deque on negative weights A negative edge can improve a vertex that already left the deque. The algorithm does not reopen settled structure the way a correct negative-edge algorithm must.
Quote O(V+E) for Dial’s algorithm on weights up to C Dial’s cost grows with C. The deque bound is the C = 1 case.

Equal positive weights belong to breadth-first search. General nonnegative weights belong to Dijkstra. Integer weights bounded by a small C belong to Dial’s algorithm.


A working example

The Bash script and the Python script run 0-1 BFS. A weight-0 edge enters the front of the deque and a weight-1 edge enters the back. Edges: 0→1 weight 0, 0→2 weight 1, 1→2 weight 1, 1→3 weight 0, 2→3 weight 1. Both print 0 0 1 0.

# neighbor lists and parallel weight lists, weights 0 or 1
nb=("1 2" "2 3" "3" "")
wt=("0 1" "1 0" "1" "")
dist=(0 1000000000 1000000000 1000000000)
# deque stored in an array with a moving head; appendleft writes in front of head
q=(0)
head=0
while (( head < ${#q[@]} )); do
  u=${q[head]}
  head=$((head+1))
  set -- ${nb[u]}
  ws=(${wt[u]})
  k=0
  for v in "$@"; do
    w=${ws[k]}
    k=$((k+1))
    nd=$((dist[u]+w))
    if (( nd < dist[v] )); then
      dist[v]=$nd
      if (( w == 0 )); then
        # rebuild with v at the front of the remaining queue
        rest=("${q[@]:head}")
        q=("$v" "${rest[@]}")
        head=0
      else
        q+=("$v")
      fi
    fi
  done
done
echo "${dist[*]}"
from collections import deque

# (neighbor, weight) with weights in {0, 1}
adj = [[(1, 0), (2, 1)], [(2, 1), (3, 0)], [(3, 1)], []]
dist = [10**9] * 4
dist[0] = 0
dq = deque([0])
while dq:
    u = dq.popleft()
    for v, w in adj[u]:
        nd = dist[u] + w
        if nd < dist[v]:
            dist[v] = nd
            if w == 0:
                dq.appendleft(v)
            else:
                dq.append(v)
assert dist == [0, 0, 1, 0]
print(*dist)

Where it is used

A 0-1 BFS is the shortest-path walk for edges whose weights are only 0 and 1, such as a maze with free steps and costly steps. Production routers with a wider integer range use Dial’s buckets or Dijkstra. The deque trick is the same idea squeezed to two weights.


When you can drop this algorithm

Drop 0-1 BFS when any weight leaves {0, 1}. Use Dijkstra, or Dial if the weights are small integers. Keep the deque when the graph really is a 0-1 graph, including state graphs where a move is either free or costs one.


Why this stays published

We publish this so a search for 0-1 BFS returns the front push for weight 0 and the back push for weight 1. 0-1 BFS is Dijkstra for weights in {0, 1}, implemented as a deque that pushes a zero-weight relaxation to the front and a one-weight relaxation to the back.

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。

Leave a Reply

Your email address will not be published. Required fields are marked *