Lesson 1 · Unit 02
Breadth-first search
Explore in rings and get the fewest hops for free
What you practise
- Queue, mark when enqueued, shortest path in hops
Try a question from this lesson
Pick one
A rumour starts with you. Every minute, everyone who knows it tells all of their friends. In what order do people hear it?
Correct answer
Your friends, then friends of friends, and so on
Why
It spreads in rings: everyone 1 step away, then everyone 2 steps away. Breadth-first search visits nodes in exactly this order, so it reaches each node by a route with the fewest steps.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
BFS uses a queue
A queue holds the nodes that are discovered but not yet explored. Take the oldest one, look at its neighbours, and add each new one to the back.
A node is marked as seen the moment it joins the queue, so it can never be added twice.
from collections import deque
def bfs(adj, start):
seen = {start}
queue = deque([start])
order = []
while queue:
node = queue.popleft()
order.append(node)
for nxt in adj[node]:
if nxt not in seen:
seen.add(nxt)
queue.append(nxt)
return orderfunction bfs(adj, start) {
const seen = new Set([start]);
const queue = [start];
let head = 0;
while (head < queue.length) {
const node = queue[head++];
for (const nxt of adj[node]) {
if (seen.has(nxt)) continue;
seen.add(nxt);
queue.push(nxt);
}
}
return queue;
}function bfs(
adj: number[][], start: number,
): number[] {
const seen = new Set([start]);
const queue = [start];
let head = 0;
while (head < queue.length) {
const node = queue[head++];
for (const nxt of adj[node]) {
if (seen.has(nxt)) continue;
seen.add(nxt);
queue.push(nxt);
}
}
return queue;
}Python notedeque.popleft() is O(1). list.pop(0) would shift every remaining item: O(n) per step.
JavaScript notequeue.shift() is O(n), so head walks forward instead. Nothing is ever removed, which makes the queue double as the visiting order.
TypeScript notenew Set([start]) is inferred as Set<number> from its first item. head walks forward because queue.shift() would cost O(n).
9 more exercises in the app
- 4× multiple choice
- 2× true or false
- 1× fill the blanks
- 1× type the answer
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.