0-1 BFS
Advanced · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
0-1 BFS finds cheapest routes when every link costs either 0 or 1. It is a double-ended queue trick: free moves go to the front of the line and paid moves to the back, giving Dijkstra-style answers with BFS-style simplicity.
Practical use cases
- Web app: Fewest line changes in a metro planner. Staying on the same line costs nothing, changing lines costs one. The planner puts free moves at the front of its queue and changes at the back, and the first arrival gives the route with the fewest changes, which commuters usually prefer to the fewest stops.
- Web app: Game grid with walls you can break. In a browser puzzle, walking on open tiles is free and smashing a wall costs one charge. The game asks for the way to the exit using the fewest smashes, and 0-1 BFS answers it for a large map instantly.
- Web app: Fixing arrows in a flow editor. A diagram tool has arrows pointing in set directions. Following an arrow is free and turning an arrow around is one edit. Finding the fewest arrow edits to connect start to finish uses this exact pattern.
- System: Game movement and routing. Maps where some terrain is free and some has a flat toll, such as toll roads or ferries, can use it instead of a heavier priority queue. The advantage is that no sorting of costs is needed, so even a large map of a million tiles is processed in a single smooth pass.
The story: The Metro Line-Changer
Mira hated changing metro lines: the stairs, the crowds, the lost tiffin box. She did not mind how many stops she rode on the same line. Her only worry was the number of line changes. So on her map, riding along one line cost 0 and stepping to another line cost 1.
Kabir said, "Use Dijkstra with a heap!" Mira laughed. "That is heavy. My costs are only 0 or 1." She used a queue like BFS, but with a twist: a free (0) move means this place is as good as where I stand now, so it should be handled immediately: she put it at the front of the queue. A costly (1) move went to the back.
Because of this, the queue was always arranged with the cheapest places at the front and slightly dearer ones at the back, just as a heap would arrange them, but without the heap's extra work. At the end every station held its fewest line changes.
This is 0-1 BFS: BFS with a double-ended queue (deque), used when every edge weighs 0 or 1.
How to spot this problem, and where you need it
You want the cheapest route, but every move costs either nothing or a single unit, and a normal BFS would treat the free moves wrongly.
Signs you need it
- The problem states costs of only 0 or 1, such as "free move" versus "one change", "one break", or "one flip".
- Plain BFS gives wrong answers because it counts every step as one, and a full Dijkstra feels heavier than needed.
- The goal is "minimum number of changes, flips or switches" rather than the number of steps.
Where to use it in a project
- Transit planners that minimise changes between lines instead of stops.
- Grid puzzle or game features with free tiles and one-cost obstacles, such as breakable walls.
The solution
Keep a double-ended queue (you can add at either end). Start with the source at cost 0. Take from the front. For each neighbour, if going there gives a smaller cost, update it; if the link costs 0, push the neighbour at the front, and if it costs 1, push it at the back. The front always holds the cheapest nodes, so each node is settled in the right order without sorting.
Payoff: Before: counting stops gave a route with 5 changes. After: the best route with only 1 change, found in one simple pass.
Explain it like I am 8
Imagine a queue at a cinema. Someone with a free VIP pass (cost 0) walks to the very front. People with normal tickets (cost 1) stand at the back. The front always has the people who have waited least.
How it works, step by step
- Set distances to infinity, start = 0. Put the start in a deque (double-ended queue).
- Pop from the front. Look at each neighbour edge with weight w.
- If
dist[u] + w < dist[v], update dist[v]. - If w = 0, push v to the front; if w = 1, push it to the back.
- Repeat until the deque is empty. A vertex may be queued twice, the second visit simply finds nothing better.
The code in four languages
PHP
<?php
// graph: node => [[neighbour, weight 0 or 1], ...]. Returns the cheapest cost to every node.
function zeroOneBfs(array $graph, string $src): array {
$dist = array_fill_keys(array_keys($graph), INF);
$dist[$src] = 0;
$dq = new SplDoublyLinkedList(); // can add/remove at both ends
$dq->push($src);
while (!$dq->isEmpty()) {
$u = $dq->shift(); // take from the front
foreach ($graph[$u] as [$v, $w]) {
if ($dist[$u] + $w < $dist[$v]) {
$dist[$v] = $dist[$u] + $w;
if ($w === 0) $dq->unshift($v); // free road: front of the line
else $dq->push($v); // paid road: back of the line
}
}
}
return $dist;
}
$graph = [
'S' => [['A', 0], ['B', 1]],
'A' => [['S', 0], ['C', 1]],
'B' => [['S', 1], ['C', 0]],
'C' => [['A', 1], ['B', 0], ['D', 0], ['T', 1]],
'D' => [['C', 0], ['T', 0]],
'T' => [['C', 1], ['D', 0]],
];
foreach (zeroOneBfs($graph, 'S') as $node => $d) echo "$node: $d\n";JavaScript
// graph: node -> [[neighbour, weight 0 or 1], ...]. Returns the cheapest cost to every node.
function zeroOneBfs(graph, src) {
const dist = {};
for (const n of Object.keys(graph)) dist[n] = Infinity;
dist[src] = 0;
const dq = [src]; // array used as a deque (fine for a demo)
while (dq.length) {
const u = dq.shift(); // take from the front
for (const [v, w] of graph[u]) {
if (dist[u] + w < dist[v]) {
dist[v] = dist[u] + w;
if (w === 0) dq.unshift(v); // free road: front of the line
else dq.push(v); // paid road: back of the line
}
}
}
return dist;
}
const graph = {
S: [['A', 0], ['B', 1]],
A: [['S', 0], ['C', 1]],
B: [['S', 1], ['C', 0]],
C: [['A', 1], ['B', 0], ['D', 0], ['T', 1]],
D: [['C', 0], ['T', 0]],
T: [['C', 1], ['D', 0]],
};
const res = zeroOneBfs(graph, 'S');
for (const node of Object.keys(res)) console.log(node + ': ' + res[node]);Java
import java.util.*;
public class Main {
record Road(String to, int weight) {}
// graph: node -> roads with weight 0 or 1. Returns the cheapest cost to every node.
static Map<String, Integer> zeroOneBfs(Map<String, List<Road>> graph, String src) {
Map<String, Integer> dist = new TreeMap<>();
for (String n : graph.keySet()) dist.put(n, Integer.MAX_VALUE);
dist.put(src, 0);
Deque<String> dq = new ArrayDeque<>(); // can add/remove at both ends
dq.addLast(src);
while (!dq.isEmpty()) {
String u = dq.removeFirst(); // take from the front
for (Road r : graph.get(u)) {
if (dist.get(u) + r.weight() < dist.get(r.to())) {
dist.put(r.to(), dist.get(u) + r.weight());
if (r.weight() == 0) dq.addFirst(r.to()); // free road: front of the line
else dq.addLast(r.to()); // paid road: back of the line
}
}
}
return dist;
}
public static void main(String[] args) {
Map<String, List<Road>> graph = Map.of(
"S", List.of(new Road("A", 0), new Road("B", 1)),
"A", List.of(new Road("S", 0), new Road("C", 1)),
"B", List.of(new Road("S", 1), new Road("C", 0)),
"C", List.of(new Road("A", 1), new Road("B", 0), new Road("D", 0), new Road("T", 1)),
"D", List.of(new Road("C", 0), new Road("T", 0)),
"T", List.of(new Road("C", 1), new Road("D", 0)));
for (var e : zeroOneBfs(graph, "S").entrySet()) System.out.println(e.getKey() + ": " + e.getValue());
}
}Go
package main
import (
"fmt"
"math"
"sort"
)
type Road struct {
to string
weight int // 0 or 1
}
// zeroOneBfs returns the cheapest cost to every node.
func zeroOneBfs(graph map[string][]Road, src string) map[string]int {
dist := map[string]int{}
for n := range graph {
dist[n] = math.MaxInt
}
dist[src] = 0
dq := []string{src} // slice used as a deque (fine for a demo)
for len(dq) > 0 {
u := dq[0] // take from the front
dq = dq[1:]
for _, r := range graph[u] {
if dist[u]+r.weight < dist[r.to] {
dist[r.to] = dist[u] + r.weight
if r.weight == 0 {
dq = append([]string{r.to}, dq...) // free road: front of the line
} else {
dq = append(dq, r.to) // paid road: back of the line
}
}
}
}
return dist
}
func main() {
graph := map[string][]Road{
"S": {{"A", 0}, {"B", 1}},
"A": {{"S", 0}, {"C", 1}},
"B": {{"S", 1}, {"C", 0}},
"C": {{"A", 1}, {"B", 0}, {"D", 0}, {"T", 1}},
"D": {{"C", 0}, {"T", 0}},
"T": {{"C", 1}, {"D", 0}},
}
dist := zeroOneBfs(graph, "S")
names := make([]string, 0, len(dist))
for n := range dist {
names = append(names, n)
}
sort.Strings(names)
for _, n := range names {
fmt.Printf("%s: %d\n", n, dist[n])
}
}Time: O(V + E) · Extra space: O(V). Each vertex is pushed only a handful of times, and a deque push or pop costs O(1). Faster than Dijkstra's heap.
Watch out for
- Pushing 0-weight neighbours to the back. Then the queue order stops being sorted by cost and answers go wrong.
- Using a normal queue (one end only). You need a deque.
- Using it when some edges weigh 2, 5 or other values. For general weights, use Dijkstra.
Quick check
- Where does a vertex reached by a 0-cost edge go?
- Back of the deque
- Front of the deque
- It is skipped
- 0-1 BFS only works when every edge weighs…
- Any positive number
- Exactly 1
- 0 or 1
- Compared with Dijkstra, 0-1 BFS time is…
- O(V + E), faster
- O((V + E) log V), same
- O(V³)