PrepStack · Markdown HTML

0-1 BFS

Ordered frontier and path · HTML

Formal shape

Relax u→v,w∈{0,1}; after improvement, appendleft for w=0 and append for w=1, keeping pending labels within adjacent cost buckets.

Recognition signals

False friends

SignalWhy it is different
All actions equalIf every edge costs one, ordinary BFS is simpler.
Weights zero and arbitrary positive valuesTwo deque ends encode only two adjacent priorities; general nonnegative weights need Dijkstra.

Core invariant

Pending candidate distances are nondecreasing from left to right; a zero edge stays in the current cost layer and a one edge enters the next.

State, transition, and processing order

ItemDefinition
StateDistance map, deque of vertices or labels, and a generator of binary-weight edges.
TransitionIf nd=dist[u]+w improves v, assign it; put v on the left for w=0 and right for w=1.
Frontier / orderA deque acting as a bucket priority queue with exactly two relative priorities.

Python skeleton

from collections import deque

def zero_one_bfs(graph, start):
    inf = float('inf')
    dist = {u: inf for u in graph}
    dist[start] = 0
    dq = deque([start])
    while dq:
        u = dq.popleft()
        for v, w in graph[u]:
            if w not in (0, 1):
                raise ValueError('weight must be 0 or 1')
            nd = dist[u] + w
            if nd < dist.get(v, inf):
                dist[v] = nd
                if w == 0:
                    dq.appendleft(v)
                else:
                    dq.append(v)
    return dist

Correctness sketch

  1. The leftmost pending label has minimum cost: zero edges remain in its layer and one edges enter only the next layer.
  2. Every relaxation creates an actual path upper bound and places an improved label at its proper relative priority.
  3. This is Dijkstra on binary weights compressed into two buckets, so the finalized distances are optimal.

Complexity

TimeSpaceParameters
O(V+E)O(V)Each successful improvement uses O(1) deque operations; standard binary-weight relaxation scans stay linear in graph size.

Edge cases

Error patterns

PatternWhy it fails / fix
Appending zero edges on the rightA free candidate falls behind costlier candidates and breaks frontier order.
Visited without distancesA vertex first seen at cost one can later improve through a free prefix.
Counting edges instead of costThe result counts one-weight edges, not total transitions.

Selection and exclusion rules

RelationTemplateBoundary
binary-weight special caseDijkstra nonnegative shortest pathA deque can encode the only two priorities.

Original micro-example

PartDetail
ResultThe minimum cost to a is 0, not its first-discovered value 1.
Setups→a costs 1, s→b costs 0, and b→a costs 0.
Tracea:1 first sits right; b:0 goes left. Popping b improves a to 0 and puts it left.

Recall prompts

My notes