You're looking for a friend in a building whose corridors keep branching. One way: check every room closest to you first, then spread out to the rooms further away. The other way: pick one corridor, follow it until it ends, then go back and try another.
The same two ways are used to explore a graph, a set of nodes (points, like towns) joined by edges (lines, like roads). In the building, the rooms are nodes and the corridors are edges. Exploring a graph means visiting every node you can reach from one starting node, one at a time. BFS (breadth-first search) spreads out first, layer by layer, like ripples on water: the closest nodes first, then the ones one step further. DFS (depth-first search) goes as deep as it can first, like walking a maze until a dead end and then going back.
BFS: spreading out layer by layer
There are six towns, A to F, with the roads A-B, A-C, B-D, B-E, C-F and E-F (all two-way). BFS uses a queue: first in, first out. This is the queue at each step, starting from A:
| Step | Take from the front | New neighbours, join at the back | Queue afterwards |
|---|---|---|---|
| 1 | A | B, C | B, C |
| 2 | B | D, E | C, D, E |
| 3 | C | F | D, E, F |
| 4 | D | (none) | E, F |
| 5 | E | (none, F was already found) | F |
| 6 | F | (none) | (empty) |
This is the graph of the six towns and the BFS function in JavaScript:
const graph = {
A: ["B", "C"],
B: ["A", "D", "E"],
C: ["A", "F"],
D: ["B"],
E: ["B", "F"],
F: ["C", "E"],
};
function bfs(graph, start) {
const visited = new Set([start]);
const queue = [start];
const order = [];
while (queue.length > 0) {
const node = queue.shift(); // take from the front
order.push(node);
for (const next of graph[node]) {
if (!visited.has(next)) {
visited.add(next);
queue.push(next); // join at the back
}
}
}
return order;
}
console.log(bfs(graph, "A")); // ["A", "B", "C", "D", "E", "F"]
graphis an adjacency list: each town keeps an array of its neighbours.queue.shift()takes the item at the very front, andqueue.push(next)putsnextat the very back.visitedis aSet: a collection that can't hold the same value twice.haschecks,addadds. A node is marked as soon as it joins the queue, so it can't join twice.orderrecords the order of visits. The result is A (layer 0), then A's neighbours B, C (layer 1), then their neighbours D, E, F (layer 2).
This graph has a cycle, a path that comes back to the node where it started: A-B-E-F-C-A. Without visited, the same towns join the queue again and again, and the while loop never ends.
Shortest distance with BFS
Because BFS works layer by layer, a node's layer number equals the fewest roads from the starting node (start) to that node. That holds in a graph without weights (an unweighted graph), where every road counts as 1. To keep the distances, change bfs a little:
- Replace
visitedwith an objectdist, starting withdist[start] = 0: the start is 0 away from itself. - Replace the check
!visited.has(next)withdist[next] === undefined, meaning the node hasn't been found yet. - Replace
visited.add(next)withdist[next] = dist[node] + 1: one road further than the node you just took. - Return
dist, notorder.
From A, the result is { A: 0, B: 1, C: 1, D: 2, E: 2, F: 2 }. The first distance written down for a node is already the shortest, because closer layers are always handled first. So never change that distance afterwards. A node that can't be reached from the starting node never gets into dist, so it isn't in the result.
DFS: go as deep as you can
DFS uses a stack: last in, first out. The easiest way to write DFS is with recursion. With recursion you don't need to build your own stack, because JavaScript already piles up unfinished calls on the call stack. This is DFS with recursion, for the same graph of six towns:
function dfs(graph, node, visited = new Set(), order = []) {
visited.add(node);
order.push(node);
for (const next of graph[node]) {
if (!visited.has(next)) dfs(graph, next, visited, order); // go deeper
}
return order; // done here: back up to the caller
}
console.log(dfs(graph, "A")); // ["A", "B", "D", "E", "F", "C"]
From A, DFS goes into B (A's first neighbour), then into D. D is a dead end: its only neighbour is B, and B is already visited. DFS goes back to B, goes into E, then F, then C through F. So C, a direct neighbour of A, is visited last.
visited = new Set() and order = [] in the parameter list are used only when no value is passed. So both are made once, in the first call dfs(graph, "A"). Every later call passes the same visited and order, so they all share the same records.
BFS or DFS?
| BFS | DFS | |
|---|---|---|
| Keeps its nodes in | a queue, first in first out (FIFO) | a stack or recursion, last in first out (LIFO) |
| Order | layer by layer | one path to a dead end, then back |
| Good for | the shortest path in a graph without weights | exploring every path, finding a way out of a maze, checking for cycles |
BFS and DFS are both O(V + E), where V is the number of nodes and E the number of edges. Every node is visited once, and every edge is checked at most twice (once from each end). So a graph twice as big takes roughly twice as long. When roads have different lengths (a weighted graph), BFS no longer gives the shortest route. That's what Dijkstra is for.
⚠️ Marked too late, distances overwritten, and giant graphs
- Marking visited when a node is taken out, not when it joins the queue. Then F could join the queue twice, from C and from E. Mark a node as soon as you
pushit into the queue. - Overwriting a distance that's already set. Without the
dist[next] === undefinedcheck, the road back from B to A changes A's distance to 2. queue.shift()on a big graph.shiftmoves every item in the array each time it runs, so it gets slow with millions of nodes. Use a pointer instead:let head = 0;thenconst node = queue[head++];.headis the index of the front item not taken yet, andhead++adds 1 to it after it is used. So the array never has to move.- Recursive DFS on a very deep graph. The call stack can fill up (stack overflow). Keep your own stack: an array with
pushandpop.
TL;DR: BFS and DFS are two ways to explore a graph: to visit every node you can reach from one starting node. BFS uses a queue (first in, first out) and visits nodes layer by layer, the closest first. So BFS fits the shortest distance in a graph without weights: dist[next] = dist[node] + 1 for neighbours that don't have a distance yet. DFS uses a stack (last in, first out) or recursion, and goes as deep as it can before going back. Both need a "visited" marker (visited or dist), so they don't run forever in a graph with a cycle (a path that comes back to where it started). Both are O(V + E): V is the number of nodes, E the number of edges.
⚡ BFS: a queue, layer by layer
Write:
function bfs(graph, start) {
const visited = new Set([start]);
const queue = [start];
const order = [];
while (queue.length > 0) {
const node = queue.shift(); // take from the front
order.push(node);
for (const next of graph[node]) {
if (!visited.has(next)) {
visited.add(next);
queue.push(next); // join at the back
}
}
}
return order;
}
Meaning: BFS explores a graph from the node start, layer by layer: the closest nodes first. graph is an adjacency list: each node keeps an array of its neighbours. BFS uses a queue: first in, first out. A node is marked in visited (a Set, a collection with no duplicates) as soon as it joins the queue. So a node can't join twice, and a graph with a cycle (a path that comes back to where it started) doesn't make the loop run forever.
⚡ Shortest distance
Meaning: To count distances, replace visited with an object dist, which holds each node's distance from the starting node. BFS works layer by layer, so in a graph without weights (every edge counts as 1), the first distance written down, dist[next] = dist[node] + 1, is already the shortest. Never change it afterwards.
⚡ DFS: go as deep as you can
Write:
function dfs(graph, node, visited = new Set(), order = []) {
visited.add(node);
order.push(node);
for (const next of graph[node]) {
if (!visited.has(next)) dfs(graph, next, visited, order); // go deeper
}
return order; // done here: back up to the caller
}
Guess first: in this graph, A is joined to B then C, B to D and E, C to F, and E to F. In a DFS from A, when is C visited?
Last of all: A, B, D, E, F, C. DFS goes into B first and keeps going deeper to a dead end before it goes back. C is reached through F.
Meaning: DFS uses a stack (last in, first out) or recursion. The default values visited = new Set() and order = [] are only used in the first call. Both are O(V + E), where V is the number of nodes and E the number of edges.