Lesson 8 · Problem-solving methods

0-1 BFS

When every edge costs 0 or 1, the shortest-path search needs no priority queue. A deque kept in distance order does the job: a vertex reached for free goes to the front, one reached for a cost of 1 goes to the back, and the front is always a vertex with the smallest known distance.

0-1 BFS concept diagramVertex u with distance 2 is popped from the front of a deque. Its neighbour v across a weight-0 edge also has distance 2 and is pushed to the front. Its neighbour w across a weight-1 edge has distance 3 and is pushed to the back. The deque holds vertices with distance 2 followed by vertices with distance 3, so it stays sorted.udist 2popped from the frontvdist 2wdist 3weight 0weight 1dequebdist 2cdist 2edist 3fdist 3push frontpush backall dist 2all dist 3front to back: d, …, d, d + 1, …, d + 1 · the front is always a closest vertex
1

When Edges Cost Only 0 or 1

Plain breadth-first search finds the fewest edges, which is the shortest path only when every edge costs the same. Dijkstra's algorithm handles any non-negative weights but pays log V per step for its heap. Between them sits a common special case: the shortest path with 0 and 1 weights.

It shows up whenever some moves are free and the rest cost one unit. Following a one-way street costs nothing, driving against it costs one fine. Walking through an open cell is free, breaking a wall costs one. Keeping a grid arrow's direction is free, changing it costs one.

  • Weights all equal: plain BFS
  • Weights only 0 and 1: 01 bfs with a deque, O(V + E)
  • Small integer weights up to k: buckets (Dial's algorithm)
  • Any non-negative weights: Dijkstra with a heap
2

The Algorithm

  1. Set dist[source] = 0, every other dist to infinity, and put the source in the deque
  2. Pop a vertex u from the front
  3. For each edge u → v with weight w: if dist[u] + w < dist[v], set dist[v] = dist[u] + w
  4. If w = 0, push v to the front; if w = 1, push v to the back
  5. Repeat until the deque is empty (or until the target is popped, if you need only one target)

The search keeps dist[v], the best cost found so far, and a double-ended queue. It is Dijkstra's loop with the heap swapped for a deque, which is why it is also called deque bfs.

  • Store (distance, vertex) in the deque, or compare against dist[], so stale entries can be skipped
  • Undirected edges: add both directions with the same weight
3

Why the Deque Stays Sorted

Dijkstra is correct because it always expands a vertex with the smallest tentative distance. The deque gives the same guarantee for free. Suppose its contents, front to back, have distances that never decrease and differ by at most 1: some entries with d, then some with d + 1.

Pop the front, distance d. A 0-edge gives a neighbour distance d, and it goes in front, still the smallest. A 1-edge gives d + 1, and it goes at the back, where the largest values already are. Either way the order holds and only two values remain. So the popped vertex is always one of the closest, and the first time a vertex is popped with its current distance, that distance is final.

Compare this with putting everything at the back. Then a vertex reached for free waits behind vertices that cost more, and if each vertex is finalised the first time it is reached, a vertex can be fixed at too high a cost. The tracer shows exactly that.

  • Invariant: front to back, distances are d, …, d, d + 1, …, d + 1
  • A 0-edge keeps d at the front; a 1-edge adds d + 1 at the back
  • So the front always holds a smallest distance, as Dijkstra's heap would
Key reference

Terms, operations, and practical uses

Key terms

  • DequeA queue that allows pushing and popping at both ends in O(1).
  • RelaxationLowering dist[v] when a cheaper route through u is found.
  • Stale entryAn old deque entry for a vertex whose distance has since improved.
  • Dial's algorithmThe bucket version for small integer weights 0..k.
Implementation

Code in Python, C++ and Java

from collections import deque

INF = float("inf")


def zero_one_bfs(n, adj, source):
    dist = [INF] * n
    parent = [-1] * n
    dist[source] = 0
    dq = deque([(0, source)])
    while dq:
        d, u = dq.popleft()
        if d > dist[u]:
            continue
        for v, w in adj[u]:
            if d + w < dist[v]:
                dist[v] = d + w
                parent[v] = u
                if w == 0:
                    dq.appendleft((dist[v], v))
                else:
                    dq.append((dist[v], v))
    return dist, parent


def undirected(n, edges):
    adj = [[] for _ in range(n)]
    for u, v, w in edges:
        adj[u].append((v, w))
        adj[v].append((u, w))
    return adj


edges = [(0, 1, 1), (0, 2, 0), (2, 1, 0), (1, 3, 1), (2, 4, 1), (3, 5, 0), (4, 5, 1)]
dist, parent = zero_one_bfs(7, undirected(7, edges), 0)
print("dist:", " ".join("inf" if d == INF else str(d) for d in dist))
path, v = [], 5
while v != -1:
    path.append(v)
    v = parent[v]
print("path to 5:", " ".join(map(str, reversed(path))))

one_way = [(0, 1), (2, 1), (2, 3), (3, 4)]
adj = [[] for _ in range(5)]
for u, v in one_way:
    adj[u].append((v, 0))
    adj[v].append((u, 1))
print("reversals 0 to 4:", zero_one_bfs(5, adj, 0)[0][4])
#include <climits>
#include <deque>
#include <iostream>
#include <tuple>
#include <utility>
#include <vector>
using namespace std;

using Graph = vector<vector<pair<int, int>>>;

pair<vector<int>, vector<int>> zeroOneBfs(const Graph& adj, int source) {
    int n = adj.size();
    vector<int> dist(n, INT_MAX), parent(n, -1);
    dist[source] = 0;
    deque<pair<int, int>> dq = {{0, source}};
    while (!dq.empty()) {
        auto [d, u] = dq.front();
        dq.pop_front();
        if (d > dist[u]) continue;
        for (auto [v, w] : adj[u]) {
            if (d + w < dist[v]) {
                dist[v] = d + w;
                parent[v] = u;
                if (w == 0) dq.push_front({dist[v], v});
                else dq.push_back({dist[v], v});
            }
        }
    }
    return {dist, parent};
}

int main() {
    vector<tuple<int, int, int>> edges = {{0, 1, 1}, {0, 2, 0}, {2, 1, 0}, {1, 3, 1}, {2, 4, 1}, {3, 5, 0}, {4, 5, 1}};
    Graph adj(7);
    for (auto [u, v, w] : edges) {
        adj[u].push_back({v, w});
        adj[v].push_back({u, w});
    }
    auto [dist, parent] = zeroOneBfs(adj, 0);
    cout << "dist:";
    for (int d : dist) {
        if (d == INT_MAX) cout << " inf";
        else cout << " " << d;
    }
    cout << "\n";
    vector<int> path;
    for (int v = 5; v != -1; v = parent[v]) path.push_back(v);
    cout << "path to 5:";
    for (auto it = path.rbegin(); it != path.rend(); ++it) cout << " " << *it;
    cout << "\n";

    vector<pair<int, int>> oneWay = {{0, 1}, {2, 1}, {2, 3}, {3, 4}};
    Graph roads(5);
    for (auto [u, v] : oneWay) {
        roads[u].push_back({v, 0});
        roads[v].push_back({u, 1});
    }
    cout << "reversals 0 to 4: " << zeroOneBfs(roads, 0).first[4] << "\n";
}
import java.util.*;

public class Main {
    static int[] dist, parent;

    static void zeroOneBfs(List<List<int[]>> adj, int source) {
        int n = adj.size();
        dist = new int[n];
        parent = new int[n];
        Arrays.fill(dist, Integer.MAX_VALUE);
        Arrays.fill(parent, -1);
        dist[source] = 0;
        Deque<int[]> dq = new ArrayDeque<>();
        dq.add(new int[]{0, source});
        while (!dq.isEmpty()) {
            int[] top = dq.pollFirst();
            int d = top[0], u = top[1];
            if (d > dist[u]) continue;
            for (int[] e : adj.get(u)) {
                int v = e[0], w = e[1];
                if (d + w < dist[v]) {
                    dist[v] = d + w;
                    parent[v] = u;
                    if (w == 0) dq.addFirst(new int[]{dist[v], v});
                    else dq.addLast(new int[]{dist[v], v});
                }
            }
        }
    }

    static List<List<int[]>> empty(int n) {
        List<List<int[]>> adj = new ArrayList<>();
        for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
        return adj;
    }

    public static void main(String[] args) {
        int[][] edges = {{0, 1, 1}, {0, 2, 0}, {2, 1, 0}, {1, 3, 1}, {2, 4, 1}, {3, 5, 0}, {4, 5, 1}};
        List<List<int[]>> adj = empty(7);
        for (int[] e : edges) {
            adj.get(e[0]).add(new int[]{e[1], e[2]});
            adj.get(e[1]).add(new int[]{e[0], e[2]});
        }
        zeroOneBfs(adj, 0);
        StringBuilder sb = new StringBuilder("dist:");
        for (int d : dist) sb.append(d == Integer.MAX_VALUE ? " inf" : " " + d);
        System.out.println(sb);
        List<Integer> path = new ArrayList<>();
        for (int v = 5; v != -1; v = parent[v]) path.add(v);
        Collections.reverse(path);
        StringBuilder p = new StringBuilder("path to 5:");
        for (int v : path) p.append(" ").append(v);
        System.out.println(p);

        int[][] oneWay = {{0, 1}, {2, 1}, {2, 3}, {3, 4}};
        List<List<int[]>> roads = empty(5);
        for (int[] e : oneWay) {
            roads.get(e[0]).add(new int[]{e[1], 0});
            roads.get(e[1]).add(new int[]{e[0], 1});
        }
        zeroOneBfs(roads, 0);
        System.out.println("reversals 0 to 4: " + dist[4]);
    }
}
Watch it run

Step through it

Running on edges 0–1:1, 0–2:0, 2–1:0, 1–3:1, 2–4:1, 3–5:0, 4–5:1

pop the front · weight 0 → push front · weight 1 → push back1001101012345DIST0: 01: ∞2: ∞3: ∞4: ∞5: ∞DEQUEfront0·0deque entries: vertex·distance, front on the left
Step 1

Free and paid edges

Edges marked 0 cost nothing, edges marked 1 cost one unit. We want the cheapest cost from 0 to every vertex, especially 5. dist[0] = 0, everything else is unknown, and the deque starts with 0. Entries are written vertex·distance.

Output
1 / 11
4

Cost, Duplicates and Stale Entries

A vertex can be improved after it was pushed: first reached by a 1-edge and pushed to the back, then reached for free and pushed to the front. Its old entry is still in the deque. When that entry comes out later, its recorded distance is larger than dist[v], so skip it. Each vertex is pushed at most once per incoming edge, so the deque sees O(E) entries.

Every entry is pushed and popped in O(1), and every edge is relaxed a bounded number of times, so the total is O(V + E) time and O(V) extra space for dist[] and the deque. That is the main reason to prefer it over Dijkstra on 0/1 weights: the same answers without the log factor.

  • Time O(V + E), space O(V + E) for the graph
  • Stale entry: recorded distance greater than dist[v]; skip it
  • Negative weights are not allowed, exactly as in Dijkstra
5

Modelling Problems as 0/1 Graphs

The skill is spotting the graph. Minimum edge reversals: given a directed graph, how many edges must be flipped so a path from s to t exists? Keep each edge u → v with cost 0 and add the reverse v → u with cost 1. The 0-1 distance from s to t is the answer.

Grids work the same way. In a maze where you may break walls, a move into an empty cell costs 0 and into a wall costs 1; the distance to the exit is the fewest walls broken. In a grid of direction arrows, following the arrow is free and changing it costs 1. A plain BFS answers neither, because it counts moves, not cost.

  • Edge reversal: original edge 0, reversed edge 1
  • Wall breaking: empty cell 0, wall 1
  • Grid arrows: follow 0, change direction 1
  • Weights other than 0 and 1 break the invariant; use Dijkstra's algorithm instead
6

Related Problems

These shortest-path problems are good next steps. Each one is a weighted search; ask first whether its weights collapse to 0 and 1.