learngraphtheory.org

Guest

Sign in to keep your graphs and progress.

Algorithm Selection

Select an algorithm and generate steps to begin visualization

0-1 BFS Visualizer

Dijkstra without a heap, when edges cost 0 or 1

Shortest paths when every edge weighs 0 or 1: a deque replaces the priority queue, 0-edges go to the front and 1-edges to the back

Time: O(V + E)
Space: O(V)
Use Case: Grids where breaking a wall costs 1, fewest turns or changes on a route, reversing as few edges as possible, competitive programming
Showing the example graph for this algorithm.
Algorithm Execution

Select an algorithm and generate steps to begin visualization

About 0-1 BFS

0-1 BFS computes shortest paths from one source when every edge weighs either 0 or 1. Plain BFS counts edges and would treat a free edge like a paid one, while Dijkstra handles the weights but pays for a priority queue. 0-1 BFS keeps a double-ended queue instead: a vertex reached over a 0-edge goes to the front, because its distance equals the current one, and a vertex reached over a 1-edge goes to the back. The deque then always holds at most two distances, d and d + 1, in sorted order, so taking the front is exactly what Dijkstra would do, in O(V + E) time with no heap at all. The method is folklore in competitive programming, where 0-1 weights turn up constantly.

How it works

Start with the source at distance 0 in the deque. Pop the front vertex, and if its recorded distance is smaller than the popped one, skip it: a better copy was taken already. Otherwise relax each edge: when the neighbour gets closer, push it at the front for a 0-edge or at the back for a 1-edge. A vertex can be pushed twice, first at the back and later at the front, which is why stale copies are skipped. The visualizer shows the deque in the panel, marks 0-edges, writes each distance in a badge and draws the shortest-path tree in green. In the example, A reaches C for free and C reaches B for free, so B, first pushed at distance 1 directly from A, is taken at distance 0, and its old copy is skipped later. All 9 vertices are reached, the farthest at distance 2, and the deque never holds more than 3 vertices.

Applications

0-1 weights model a choice between a free move and a costly one. On grids it gives the fewest walls to break to reach a cell, or the fewest direction changes on a route when moving straight is free and turning costs 1. In a directed graph, adding each edge reversed with weight 1 lets 0-1 BFS find the fewest edges to reverse so that a path exists. It counts the fewest line changes on a transit map, where riding a line is free and switching costs one, and the fewest flips in many puzzle and state-space problems. It is a staple of competitive programming because it is shorter and faster than Dijkstra, and it generalises to small integer weights with Dial's bucket queue.

Pseudocode

A deque replaces the priority queue: 0-edges push to the front, 1-edges to the back.

ZeroOneBFS(G, s):
    dist(v) = infinity for every v, dist(s) = 0
    D = a deque holding (s, 0)
    while D is not empty:
        (u, d) = pop the front of D
        if d > dist(u): continue               // a better copy was taken
        for each edge (u, v) with weight w in {0, 1}:
            if dist(u) + w < dist(v):
                dist(v) = dist(u) + w
                if w = 0: push (v, dist(v)) at the front of D
                else: push (v, dist(v)) at the back of D
    return dist

Invariant: the deque holds keys d, …, d, d + 1, …, d + 1 in that order, where d is the key at the front. A 0-edge pushes key d at the front and a 1-edge pushes key d + 1 at the back, so the order survives. Taking the front is therefore the same choice Dijkstra makes with a heap.

Worked example, step by step

The nine-vertex example loaded on this page, from A.

Example graph: Vertices A to I and 13 edges. Five are free: A–C, C–B, D–E, D–G and F–H. The other eight weigh 1.

  1. Pop A (0). A–C weighs 0, so C goes to the front with 0. A–B weighs 1, so B goes to the back with 1.
  2. Pop C (0). C–B weighs 0 and B improves from 1 to 0, so B goes to the front. C–E weighs 1: E goes to the back with 1. B is now in the deque twice.
  3. Pop B (0), later B (1). B (0) pushes D at the back with 1. The old copy of B with key 1 comes out later and is skipped, because B already has distance 0.
  4. Distance 1. E (1) pushes F at the back with 2. D (1) pushes G at the front with 1 over the free edge D–G, so G is taken before F. G pushes I with 2.
  5. Distance 2. F (2) pushes H at the front with 2 over the free edge F–H. H and I improve nothing.

All 9 vertices reached: A, B, C at 0, D, E, G at 1, F, H, I at 2. The deque never held more than 3 vertices.

Complexity, and where it comes from

Time: O(V + E) · Space: O(V)

Each vertex is processed once, when its first copy with the final distance leaves the deque, and later copies are skipped in O(1). Processing a vertex looks at each of its edges once, so edges are examined O(E) times in all, and every push comes from one such examination. Deque operations are O(1), so the total is O(V + E), against O((V + E) log V) for Dijkstra with a binary heap. Dial's algorithm extends the idea to integer weights up to C with C + 1 buckets, in O(V·C + E).

When to use 0-1 BFS, and when not to

Shortest path methods by the weights they allow.

AlternativePrefer it whenCost
BFSAll edges weigh the same. A plain queue is enough.O(V + E)
DijkstraWeights are arbitrary non-negative numbers.O((V + E) log V)
Dial's algorithmWeights are small integers from 0 to C. One bucket per distance, scanned in order.O(V·C + E)

Common pitfalls

  • Marking vertices when they are pushed. In BFS a vertex is often marked as it enters the queue. Here B enters with 1 and later improves to 0, so a mark on entry would freeze the wrong distance. Mark at pop time, or compare with dist as above.
  • Not skipping stale copies. A vertex can sit in the deque twice. Processing the stale copy again leaves the distances right but wastes work, and in variants that record parents or count paths it corrupts them.
  • Using other weights. An edge of weight 2 pushed at the back breaks the sorted order of the deque. For larger weights split edges into unit steps, use Dial's buckets, or use Dijkstra.

Frequently asked questions

Why not plain BFS?
BFS takes vertices in order of the number of edges, so it would settle B at cost 1 over the direct edge before seeing the two free steps A, C, B. 0-1 BFS orders vertices by cost instead.
Where do 0-1 weights come from?
From choices between a free and a costly move: walking through open cells or breaking a wall, going straight or turning, following an edge in its direction or reversing it, staying on a line or changing. Many contest problems hide such a graph.
Is 0-1 BFS the same as Dijkstra?
It makes the same choices, so it returns the same distances. It replaces the heap by a deque, which works only because no more than two distinct keys are ever waiting.

Related algorithms: Breadth-First Search, Dijkstra's Algorithm, Δ-Stepping (Parallel Shortest Paths), Uniform Cost Search (UCS), Bidirectional BFS

Built by Mohammed Islam HadjoudjWork with me

An example graph: you can change it, or start blank.

Zoom Controls

30%
Nodes: 9
Edges: 13