Your motorbike key is lost somewhere in the house. One way: glance into every room on the ground floor, then go upstairs. The other: walk into one bedroom, open the wardrobe, open the deepest drawer, and only move to another room if the key isn't there. Both ways check every spot in the end, only in a different order.
Walking through a graph means: start at one node, then visit every node you can reach along the edges, each one once. BFS (breadth-first search) is like the first way. It spreads out first: all the neighbours of the start node, then the nodes further away. DFS (depth-first search) is like the second way. It dives first: it keeps going along one path until it reaches a dead end (no new node), then goes back and tries another path.
BFS: layer by layer, with a queue
This code runs BFS, starting from node A:
const graph = {
A: ["B", "C"],
B: ["A", "D", "E"],
C: ["A", "E", "F"],
D: ["B"],
E: ["B", "C"],
F: ["C"],
};
function bfs(graph, start) {
const order = [];
const queue = [start]; // nodes waiting to be visited
const seen = new Set([start]); // nodes already found
while (queue.length > 0) {
const node = queue.shift(); // take from the front
order.push(node);
for (const next of graph[node]) {
if (!seen.has(next)) {
seen.add(next);
queue.push(next); // join the back
}
}
}
return order;
}
console.log(bfs(graph, "A")); // ["A", "B", "C", "D", "E", "F"]
graphis an adjacency list. Each node's neighbours are handled in the order of its array.queueis a waiting line: nodes join at the back (push) and leave from the front (shift), so a node found first is visited first.seenis aSetof the nodes already found. Withoutseen, A finds B, then B finds A again, and the loop never stops.- A node is marked in
seenwhen it joins the queue, not when it's visited (taken from the queue and recorded inorder), so the same node can't join the queue twice.
These are the steps:
| Take | New neighbours, joining the queue | Queue after | Visit order |
|---|---|---|---|
| A | B, C | B, C | A |
| B | D, E | C, D, E | A, B |
| C | F (A and E are already found) | D, E, F | A, B, C |
| D, E, F | (none) | (empty) | A, B, C, D, E, F |
So the order is A, then A's neighbours (B, C), then the nodes 2 edges away from A (D, E, F): layer by layer.
DFS: as deep as possible
This code runs DFS on the same graph, also starting from A:
function dfs(graph, node, seen = new Set(), order = []) {
seen.add(node);
order.push(node);
for (const next of graph[node]) {
if (!seen.has(next)) dfs(graph, next, seen, order); // go deeper first
}
return order;
}
console.log(dfs(graph, "A")); // ["A", "B", "D", "E", "C", "F"]
DFS goes straight into the first neighbour it hasn't visited, by calling itself (recursion). From A to B, from B to D. D is a dead end, so it goes back to B and continues to E. From E to C, from C to F.
The calls still waiting (for example the call for B, while D is checked) are kept on the call stack, so DFS really uses a stack, while BFS uses a queue.
Why BFS finds the shortest path
The shortest path here means the path with the fewest edges. BFS visits every node 1 edge away from the start, then every node 2 edges away, and so on. So the first time BFS finds a node, its path is the shortest one. In the example graph, BFS finds F through A, C, F (2 edges), while DFS goes through A, B, E, C, F (4 edges). So for the shortest way to the exit of a maze, use BFS.
This holds in a graph without weights (unweighted), where every edge counts as the same length. If edges have weights, such as distances in km, use Dijkstra (the next lesson). Both BFS and DFS visit every node once and check every edge, so their time grows with the number of nodes plus the number of edges.
⚠️ Loops that never end, and nodes that appear twice
- No
seen. A graph can have cycles, so the same nodes are visited again and again and the loop never stops. - Marking too late. If a node is only marked when it's taken out of the queue, the same node can join the queue twice and appear twice in the result.
- Taking from the back.
queue.pop()takes the node that joined last, so the walk dives like DFS. BFS always takes from the front withshift(). shift()on a big graph.shiftmoves every item in the array. For a very long queue, use an index marker, as in the queue lesson:const node = queue[head++]withlet head = 0.
TL;DR: BFS (breadth-first search) and DFS (depth-first search) are two ways to walk through a graph: to visit every node you can reach along the edges, each one once. BFS moves layer by layer (nodes 1 edge away first, then 2 edges) with a queue: take a node from the front, add its new neighbours to the back. DFS goes as deep as it can with recursion (the call stack is its stack), then goes back at a dead end. BFS guarantees the shortest path (the fewest edges) in an unweighted graph. Both need to record the nodes already found in a Set, because a graph can have cycles (paths that come back to where they started).
⚡ BFS: layer by layer
Write:
const node = queue.shift(); // take from the front
order.push(node);
for (const next of graph[node]) {
if (!seen.has(next)) {
seen.add(next);
queue.push(next); // join the back
}
}
Meaning: This is the core of BFS (breadth-first search), a way to walk through a graph layer by layer: first the nodes 1 edge from the start node, then the nodes 2 edges away. queue holds the nodes waiting to be visited: a node is taken from the front, and its new neighbours join the back. graph[node] is that node's array of neighbours. order records the visit order. seen is a Set of the nodes already found: a node is marked when it joins the queue, so it can't join twice.
⚡ DFS: as deep as possible
Meaning: DFS (depth-first search) goes straight into the first neighbour it hasn't visited, by calling itself (recursion). DFS goes back at a dead end (no new neighbours). The calls still waiting are kept on the call stack, so DFS uses a stack, while BFS uses a queue.
⚡ The shortest path
Guess first: in an unweighted graph (every edge counts the same), which one is guaranteed to find the shortest path (the fewest edges), BFS or DFS?
BFS. It visits every node 1 edge from the start, then every node 2 edges away, and so on. So it first finds each node through the fewest edges.
Meaning: If edges have weights, such as distances in km, use Dijkstra (the next lesson). BFS and DFS both need seen (the record of the nodes already found), because a graph can have cycles: paths that come back to where they started.