0-1 BFS: a deque instead of a heap

Video lessonComing soon

1 Free roads and toll roads

The city from the graph lessons has new rules. Some roads are free, and some charge a toll of one coin. We want the fewest coins from junction 0 to every other junction.

1001010123456
Roads marked 1 charge a coin. Roads marked 0 are free

Plain BFS gets this wrong. It reaches junction 1 first, by the toll road, marks it and stores 1 coin. The free route 0, 2, 1 arrives one ripple later, and the mark turns it away. BFS returns [0, 1, 0, 2, 2, -1, -1], but junctions 1, 3 and 4 really cost 0, 1 and 1.

Dijkstra's algorithm gets it right, because it takes junctions in order of coins, not roads. But its heap costs O(log V) for every push and pop. With weights of only 0 and 1, a deque can do the heap's job in O(1) per step. That is 0-1 BFS.

2 The deque holds only two distances

Dijkstra pops the smallest label, d. Each road from there gives its neighbour d + 0 or d + 1. So every label waiting in the heap is d or d + 1, never anything else. Section 4 proves it.

A heap is wasted on two values. A deque does the sorting for free if we keep the d's at the front and the d + 1's at the back:

  • A free road gives v the label d, the same as the front. So v goes to the front.
  • A toll road gives v the label d + 1, the largest label waiting. So v goes to the back.
ddd + 1d + 1frontback
The deque's labels: d in front, d + 1 behind

The deque works as a priority queue with only two buckets. Popping the front always gives the smallest label, just as the heap did.

Everything else is Dijkstra: the labels in dist, relaxing a road only when it lowers a label, and skipping stale entries.

3 Tracing the city

Each entry is a pair (distance, junction), as in the Dijkstra lesson. In the steps, filled junctions are finished, and the purple one is being taken. Each number is a label, and bold roads gave the labels. The deque runs front to back, left to right, with the popped entry crossed and new ones in orange.

0-1 BFS from junction 0
100101001∞2∞3∞4∞5∞6∞
(0, 0)
Start: dist[0] = 0, deque (0, 0)

The same run as a table, with dist for junctions 0 to 4:

PoppedPushedDeque afterdist after
(0, 0)(0, 2) front, (1, 1) back(0, 2), (1, 1)0, 1, 0, ∞, ∞
(0, 2)(0, 1) front(0, 1), (1, 1)0, 0, 0, ∞, ∞
(0, 1)(1, 3) back(1, 1), (1, 3)0, 0, 0, 1, ∞
(1, 1)stale, 1 > 0(1, 3)0, 0, 0, 1, ∞
(1, 3)(1, 4) front(1, 4)0, 0, 0, 1, 1
(1, 4)noneempty0, 0, 0, 1, 1

Read the "Deque after" column. The 0's always sit in front of the 1's, so the deque stays sorted without ever comparing two entries. Junction 1 went in twice, first at the back with 1 and then in front with 0. The front copy came out first, and the old copy was stale when its turn came.

4 Why the deque stays sorted

The claim is that the labels in the deque, front to back, never go down, and the last is at most the first plus 1. In short, they look like d, …, d, d + 1, …, d + 1.

  1. At the start, the deque holds only (0, source). The claim holds.
  2. We pop the front, with label d. What is left still runs from d to at most d + 1.
  3. A free road pushes d at the front. Nothing behind it is smaller.
  4. A toll road pushes d + 1 at the back. Nothing in front of it is larger, and the last label is still at most d + 1.

So the deque hands out labels in increasing order, the same order the heap would. The Dijkstra lesson proved that the smallest waiting label is final, and that proof holds here word for word.

Step 4 needs every weight to be 0 or 1. A road of 2 would push d + 2, and a later road of 1 would then push d + 1 behind it. The deque would no longer be sorted.

5 The code, and what it costs

The code is the Dijkstra code with the heap swapped for a deque. It takes the same adjacency list, where adj[u] holds (neighbour, weight) pairs, and returns dist with -1 for a junction it cannot reach. Only the push changes: a free road pushes at the front and a toll road at the back.

On the city, it returns [0, 0, 0, 1, 1, -1, -1].

C++

deque has both ends. push_front, push_back and pop_front are all O(1). A vector with insert at begin() shifts every value, so it is O(n).

ArrayDeque is the deque. offerFirst, offerLast and pollFirst are all O(1). An ArrayList with add(0, x) shifts every value, so it is O(n).

collections.deque, not a list. appendleft and popleft are O(1). A list's insert(0, x) shifts every value, so it is O(n).

No built-in deque, so the tab carries one. unshift puts a value in front, but it moves every value, so it is O(n). The Deque class keeps the front part in its own array, so every step is O(1).

container/list is a doubly linked list. PushFront, PushBack and Remove are O(1). Remove returns the value as any, so .(entry) turns it back into an entry.

VecDeque is the deque. push_front, push_back and pop_front are O(1). pop_front returns an Option, so while let stops when the deque is empty.

LinkedList<T> as the deque. C# has no deque type, but AddFirst, AddLast and RemoveFirst on a linked list are all O(1). List<T>.Insert(0, x) shifts every value, so it is O(n).

Cost. When v first gets a label, the junction just popped has label d, and nothing waiting is below d. So v's first label is d or d + 1, and it can drop at most once more, from d + 1 to d. Each junction joins the deque at most twice, and the stale check lets only one copy read its roads. So 0-1 BFS takes O(V + E) time, the same as BFS. dist and the deque take O(V) space.

V = 10⁵, E = 2 × 10⁵StepsNeeds
Dijkstraabout 5 × 10⁶a heap
0-1 BFSabout 5 × 10⁵a deque

Both pass the time limit. 0-1 BFS does about a tenth of the work, and in a language without a heap it is much less code.

6 Grids with free and paid moves

The problems in this pattern give a grid, not a list of roads. As in the BFS lesson, each cell is a vertex and its neighbours are the four cells around it. The only new question is what each move costs.

  • Obstacles. Some cells hold a rock. Stepping onto an empty cell is free, and stepping onto a rock means removing it, which costs 1. The weight of a move is the value of the cell it lands on.
  • Signs. Each cell has an arrow. The move the arrow points to is free. Any other move means changing the sign first, which costs 1.
010011010010
Rocks are 1. Moving onto one costs 1
011112121122
dist: the fewest rocks to reach each cell
→↓←↑→↑←←↑
Signs: following the arrow is free, any other move costs 1

The deque then holds cells instead of junctions. We work out the four moves as we go, with the same bounds check as in the BFS lesson:

pop (d, r, c) from the front
if d > dist[r][c]: skip it
for each move to (nr, nc) inside the grid:
    w = the move's cost, 0 or 1
    if d + w < dist[nr][nc]:
        dist[nr][nc] = d + w
        if w is 0: push (d, nr, nc) at the front
        else: push (d + 1, nr, nc) at the back

A grid of R rows and C columns has R × C vertices and at most 4 moves from each, so this is O(R × C).

7 Mistakes, and when to use it

  • Marking a junction done when it is pushed. That is plain BFS again. Junction 1 is pushed first with 1 coin, keeps it, and the code returns [0, 1, 0, 2, 2, -1, -1]. A label is final only when it is popped.
  • Pushing free roads to the back. The deque is then an ordinary queue, and labels come out unsorted. On the city, 3 and 4 first get 2 and are fixed later. The answers still come out right, but junctions are taken 8 times instead of 5, and a big graph gets TLE.
  • Pushing without the < check. Junctions 0 and 2 share a free road. Each one pushes the other at the front, again and again, and the loop never ends. Push only when the label really drops.
  • A front insert that shifts. Adding at the front of an array moves every value, so each push is O(n), and a big grid gets TLE. The note under the code names the right type for each language.

The sign is a cheapest-route question where every move costs 0 or 1: free moves and paid ones, or the fewest of something to remove, break or change. The costs pick the tool. BFS fits when every move costs 1, 0-1 BFS when some moves are free, and Dijkstra when costs are larger.

When weights are small whole numbers, say 0 to 5, the same idea grows into Dial's algorithm: one bucket per distance, in place of two ends of a deque.

The next lesson leaves shortest routes behind. A minimum spanning tree connects every junction at the lowest total cost.

Before reaching for a heap, read the weights. If every weight is 0 or 1, a deque is enough: free moves to the front, paid moves to the back.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.