Skip to lesson

0-1 BFS computes shortest paths on graphs with edge weights 0 and 1. It achieves O(V + E) time using ArrayDeque.

Graphs with binary weights of zero and one

Standard BFS finds shortest paths when every edge has equal weight 1. Dijkstra algorithm handles arbitrary positive weights using a PriorityQueue in O(E log V) time. However, many problems feature only two edge weights: 0 and 1.

Example 1 · Brute force: repeat every edge until nothing changes, O(V * E)

Main.javaJava
import java.util.*;
public class Main {    public static void main(String[] args) {        int n = 4;        int[][] edges = {{0, 1, 1}, {0, 2, 0}, {2, 3, 1}, {1, 3, 0}};        int[] dist = new int[n];        Arrays.fill(dist, Integer.MAX_VALUE);        dist[0] = 0;
        boolean changed = true;        while (changed) {            changed = false;            for (int[] e : edges) {                if (dist[e[0]] != Integer.MAX_VALUE && dist[e[0]] + e[2] < dist[e[1]]) {                    dist[e[1]] = dist[e[0]] + e[2];                    changed = true;                }            }        }        System.out.println("Shortest 0-1 distance 0 to 3: " + dist[3]);    }}
Output
Shortest 0-1 distance 0 to 3: 1

What this code does

  • Each pass relaxes every edge, so the cost is O(V * E) in the worst case.
  • It ignores that every weight is only 0 or 1.
  • The next two examples use that fact to do far less work.

Example 2 · Better: Dijkstra with a heap, O((V + E) log V)

Main.javaJava
import java.util.*;
public class Main {    public static void main(String[] args) {        int n = 4;        int[][] edges = {{0, 1, 1}, {0, 2, 0}, {2, 3, 1}, {1, 3, 0}};        List<List<int[]>> adj = new ArrayList<>();        for (int i = 0; i < n; i++) adj.add(new ArrayList<>());        for (int[] e : edges) adj.get(e[0]).add(new int[]{e[1], e[2]});
        int[] dist = new int[n];        Arrays.fill(dist, Integer.MAX_VALUE);        dist[0] = 0;        PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0]));        pq.offer(new int[]{0, 0});
        while (!pq.isEmpty()) {            int[] cur = pq.poll();            if (cur[0] > dist[cur[1]]) continue;            for (int[] e : adj.get(cur[1])) {                if (dist[cur[1]] + e[1] < dist[e[0]]) {                    dist[e[0]] = dist[cur[1]] + e[1];                    pq.offer(new int[]{dist[e[0]], e[0]});                }            }        }        System.out.println("Shortest 0-1 distance 0 to 3: " + dist[3]);    }}
Output
Shortest 0-1 distance 0 to 3: 1

What this code does

  • Dijkstra works for any non-negative weights, so it is correct here.
  • Each heap push and pop costs O(log V).
  • With only two weights the heap is more than needed: a deque can keep the same order for free.

Example 3 · Optimal: 0-1 BFS with a deque, O(V + E) time

Main.javaJava
import java.util.*;
public class Main {    static class Edge {        int to, weight;        Edge(int to, int weight) { this.to = to; this.weight = weight; }    }
    static int zeroOneBfs(int n, List<List<Edge>> adj, int src, int target) {        int[] dist = new int[n];        Arrays.fill(dist, Integer.MAX_VALUE);        Deque<Integer> deque = new ArrayDeque<>();
        dist[src] = 0;        deque.offerFirst(src);
        while (!deque.isEmpty()) {            int u = deque.pollFirst();            if (u == target) return dist[u];
            for (Edge e : adj.get(u)) {                int v = e.to;                int w = e.weight;                if (dist[u] + w < dist[v]) {                    dist[v] = dist[u] + w;                    if (w == 0) deque.offerFirst(v);                    else deque.offerLast(v);                }            }        }        return dist[target] == Integer.MAX_VALUE ? -1 : dist[target];    }
    public static void main(String[] args) {        int n = 4;        List<List<Edge>> adj = new ArrayList<>();        for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
        adj.get(0).add(new Edge(1, 1));        adj.get(0).add(new Edge(2, 0));        adj.get(2).add(new Edge(3, 1));        adj.get(1).add(new Edge(3, 0));
        System.out.println("Shortest 0-1 distance 0 to 3: " + zeroOneBfs(n, adj, 0, 3));    }}
Output
Shortest 0-1 distance 0 to 3: 1

What this code does

  • Weight 0 edges are pushed to the front with offerFirst for immediate processing.
  • Weight 1 edges are pushed to the back with offerLast.
  • Shortest path from 0 to 3 costs 1 along path 0 -> 2 -> 3.
  • A deque keeps distances in order using the front for weight 0 and the back for weight 1, so there is no log V heap cost.

Using Dijkstra on 0-1 graphs works correctly, but incurs logarithmic heap overhead per edge. Brute force BFS explores without cost awareness, discovering suboptimal paths first. Re-visiting nodes when cheaper paths arrive turns standard BFS into exponential search. 0-1 BFS achieves linear O(V + E) time using a double-ended queue (ArrayDeque). When relaxing an edge with weight 0, push the destination to the front with offerFirst. When relaxing an edge with weight 1, push the destination to the back with offerLast.

Why the double-ended queue maintains order

A standard BFS queue maintains vertices whose distances differ by at most 1. At any moment, elements in the queue have distance either d or d + 1. The 0-1 BFS deque keeps that order by choosing which end each neighbour joins (shown after the code).

Java
int u = deque.pollFirst();for (Edge e : adj.get(u)) {    int nd = dist[u] + e.weight;    if (nd < dist[e.to]) {        dist[e.to] = nd;        if (e.weight == 0) deque.offerFirst(e.to); // same distance d: front        else deque.offerLast(e.to);                // distance d + 1: back    }}

When popping a vertex u with distance d, an edge of weight 0 yields distance d. Distance d is strictly less than d + 1. Therefore, that neighbour must be processed before any d + 1 node. Adding that neighbour to the front of the deque preserves non-decreasing distance ordering.

An edge of weight 1 leads to distance d + 1. Adding that neighbour to the back of the deque places it behind existing d nodes. Consequently, the deque always holds elements with at most two distinct distance levels.

Find the bug

Spot the 0-1 BFS bug

Select the line that is wrong.

A weight-0 neighbour must be processed next.

Round 1 of 2

Minimum cost to make a valid grid path

Consider a grid where each cell contains a directional arrow. You want to travel from top-left (0, 0) to bottom-right (R - 1, C - 1). Modifying any arrow costs 1 unit, while following an arrow costs 0.

Example 4 · Minimum Cost to Make Valid Path in Grid

Main.javaJava
import java.util.*;
public class Main {    // 1: right, 2: left, 3: down, 4: up    static int minCost(int[][] grid) {        int m = grid.length;        int n = grid[0].length;        int[][] dist = new int[m][n];        for (int[] row : dist) Arrays.fill(row, Integer.MAX_VALUE);
        int[][] dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};        Deque<int[]> deque = new ArrayDeque<>();
        dist[0][0] = 0;        deque.offerFirst(new int[]{0, 0});
        while (!deque.isEmpty()) {            int[] curr = deque.pollFirst();            int r = curr[0];            int c = curr[1];            if (r == m - 1 && c == n - 1) return dist[r][c];
            for (int i = 0; i < 4; i++) {                int nr = r + dirs[i][0];                int nc = c + dirs[i][1];                if (nr >= 0 && nr < m && nc >= 0 && nc < n) {                    int cost = (grid[r][c] == i + 1) ? 0 : 1;                    if (dist[r][c] + cost < dist[nr][nc]) {                        dist[nr][nc] = dist[r][c] + cost;                        if (cost == 0) deque.offerFirst(new int[]{nr, nc});                        else deque.offerLast(new int[]{nr, nc});                    }                }            }        }        return dist[m - 1][n - 1];    }
    public static void main(String[] args) {        int[][] grid = {            {1, 1, 1, 1},            {2, 2, 2, 2},            {1, 1, 1, 1},            {2, 2, 2, 2}        };        System.out.println("Min cost to reach end: " + minCost(grid));    }}
Output
Min cost to reach end: 3

What this code does

  • Moving along grid arrow costs 0 and pushes coordinates to deque front.
  • Changing arrow direction costs 1 and pushes coordinates to deque back.
  • Minimum changes needed to reach destination is 3 in O(M * N) time.

Example 5 · Minimum Obstacle Removal in Grid

Main.javaJava
import java.util.*;
public class Main {    static int minimumObstacles(int[][] grid) {        int m = grid.length;        int n = grid[0].length;        int[][] dist = new int[m][n];        for (int[] row : dist) Arrays.fill(row, Integer.MAX_VALUE);
        Deque<int[]> deque = new ArrayDeque<>();        dist[0][0] = 0;        deque.offerFirst(new int[]{0, 0});
        int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
        while (!deque.isEmpty()) {            int[] curr = deque.pollFirst();            int r = curr[0];            int c = curr[1];            if (r == m - 1 && c == n - 1) return dist[r][c];
            for (int[] d : dirs) {                int nr = r + d[0];                int nc = c + d[1];                if (nr >= 0 && nr < m && nc >= 0 && nc < n) {                    int w = grid[nr][nc]; // 0 for empty, 1 for obstacle                    if (dist[r][c] + w < dist[nr][nc]) {                        dist[nr][nc] = dist[r][c] + w;                        if (w == 0) deque.offerFirst(new int[]{nr, nc});                        else deque.offerLast(new int[]{nr, nc});                    }                }            }        }        return dist[m - 1][n - 1];    }
    public static void main(String[] args) {        int[][] grid = {            {0, 1, 1},            {1, 1, 0},            {1, 1, 0}        };        System.out.println("Obstacles removed: " + minimumObstacles(grid));    }}
Output
Obstacles removed: 2

What this code does

  • Empty cells are free transitions with weight 0 pushed to front.
  • Obstacle cells cost 1 obstacle removal and are pushed to back.
  • Finds path with minimum obstacle removals in O(M * N) linear time.

Moving in the direction of the existing arrow has edge weight 0. Moving in any of the other three directions has edge weight 1. This forms an implicit graph with edge weights in 0 and 1. Initialise dist[0][0] = 0 and push (0, 0) to the deque. For each polled cell, inspect four adjacent directions. Add zero-cost moves to the front and one-cost moves to the back in O(R * C) time.

Next step

Check your understanding

10 quick questions