7 / 7 · Basic
Graph search: BFS and DFS
In 1736 Leonhard Euler showed that no walk crosses each of Königsberg's seven bridges exactly once, and graph theory began with that answer.
Jump to the 11 practice questionsYou will learn
- Run breadth-first search with a queue
- Run depth-first search with the call stack
Before this: Recursion
1Explain
Dots and lines
A graph is a set of points, called vertices or nodes, joined by lines, called edges. The idea is plain, and it fits a huge range of things: cities joined by roads, web pages joined by links, people joined by friendships, squares of a maze joined where there is no wall. Once a problem is drawn as a graph, the same handful of algorithms can answer questions like "can I get from here to there?" and "what is the shortest way?"
The example graph in this unit. A is the start; F is the goal. Edges: A‑B, A‑C, B‑D, C‑D, C‑E, D‑F, E‑F.
2Problem
Count the edges
How many edges does the example graph have?
Hint
Count each line once.
Solution
Answer: 7
Count each connection once: A-B, A-C, B-D, C-D, C-E, D-F, E-F.
3Explain
Storing a graph in code
A common way to store a graph is an adjacency list: for each vertex, a list of its neighbours. MIT's 6.006 notes use exactly this, an array or dictionary Adj where Adj[u] lists the vertices joined to u. For the graph above it looks like this:
const graph = {
A: ["B", "C"],
B: ["A", "D"],
C: ["A", "D", "E"],
D: ["B", "C", "F"],
E: ["C", "F"],
F: ["D", "E"],
};
console.log(graph.C);
console.log(graph.C.length);["A","D","E"]
34Explore
Breadth-first search: ring by ring
Breadth-first search (BFS) explores a graph in rings around the start. First the start itself, at distance 0. Then all its neighbours, at distance 1. Then every new vertex next to those, at distance 2, and so on. To do this it keeps a queue, a line where the first one in is the first one out. Take the vertex at the front of the queue, visit it, and add its unseen neighbours to the back.
The queue holds vertices that are found but not yet visited. Green vertices are visited, light blue ones are waiting in the queue.
Put A in the queue and mark it seen.
5Problem
BFS order
Put the vertices in the order BFS from A visits them (neighbours taken in alphabetical order).
- D
- C
- A
- E
- F
- B
Hint
Distance 0, then 1, then 2, then 3 from A.
Solution
Answer:
- A
- B
- C
- D
- E
- F
Distance 0: A. Distance 1: B, C. Distance 2: D (from B), E (from C). Distance 3: F.
6Problem
BFS uses
Which data structure does breadth-first search use?
Hint
The first vertex found is the first visited.
Solution
Answer: A queue (first in, first out)
Vertices found first are visited first, which gives the ring-by-ring order.
7Problem
Shortest path to F
In the example graph, how many edges are on the shortest path from A to F?
Hint
BFS reached F in its third ring.
Solution
Answer: 3
BFS levels: A 0; B, C 1; D, E 2; F 3. For example A, B, D, F.
8Explore
Depth-first search: as far as you can
Depth-first search (DFS) behaves like a person in a maze keeping one hand on the wall. It follows one path as deep as it can go. When it reaches a dead end or a place it has already seen, it backs up to the most recent choice point and tries the next option. It uses a stack instead of a queue, last in, first out, and is very natural to write with recursion, where the call stack does the remembering.
The call stack holds the vertices whose calls are still running. A new vertex goes on top; when it has no unseen neighbour left, the search backs up.
Visit A.
9Problem
DFS order
Put the vertices in the order recursive DFS from A visits them (neighbours in alphabetical order).
- E
- D
- C
- B
- F
- A
Hint
From D the first unseen neighbour is C.
Solution
Answer:
- A
- B
- D
- C
- E
- F
A → B → D (B's first unseen neighbour) → C (D's first unseen) → E (C's next unseen) → F.
10Explain
Which one to use
In the lab's first maze, BFS visits 105 squares and finds a path of 22 moves, the shortest possible. DFS happens to dive toward the goal and visits only 31 squares, but its path takes 28 moves. Neither is always cheaper. With a queue that takes constant time to add or remove an item, BFS takes O(V + E) time. V counts vertices, and E counts edges.
11Problem
Fewest edges
Which search is guaranteed to find a path with the fewest edges?
Hint
Which search finishes each ring before the next?
Solution
Answer: BFS
BFS reaches every vertex at distance d before any vertex at distance d + 1.
12Problem
Friend of a friend
You want to know the fewest friend-of-a-friend links between two people in a social network. Which search?
Hint
Fewest links means fewest edges.
Solution
Answer: BFS
Fewest links means fewest edges, which is what BFS finds.
13Problem
Remembering what was seen
Why must BFS and DFS remember which vertices they have seen?
Hint
The graph has a loop: A, B, D, C and back to A.
Solution
Answer: Otherwise a loop in the graph would make the search go round forever
Remembering seen vertices also keeps the running time at O(V + E).
14Problem
Running time
What is the running time of BFS on a graph with V vertices and E edges?
Hint
Each vertex is queued once; each list is read once.
Solution
Answer: O(V + E)
Each vertex enters the queue once and each adjacency list is read once.
15Practice
Complete BFS
Complete BFS so it prints A B C D E F.
A B C D E Fconst graph = { A: ["B", "C"], B: ["A", "D"], C: ["A", "D", "E"], D: ["B", "C", "F"], E: ["C", "F"], F: ["D", "E"] };
function bfs(start) {
const seen = new Set([start]);
const queue = [start];
const order = [];
// While the queue is not empty: take the front vertex,
// add it to order, queue its unseen neighbours.
return order;
}
console.log(bfs("A").join(" "));
Hint
Take from the front with shift(); pop() takes from the back and turns the queue into a stack.
A solution
const graph = { A: ["B", "C"], B: ["A", "D"], C: ["A", "D", "E"], D: ["B", "C", "F"], E: ["C", "F"], F: ["D", "E"] };
function bfs(start) {
const seen = new Set([start]);
const queue = [start];
const order = [];
while (queue.length > 0) {
const u = queue.shift();
order.push(u);
for (const v of graph[u]) {
if (!seen.has(v)) { seen.add(v); queue.push(v); }
}
}
return order;
}
console.log(bfs("A").join(" "));16Practice
Write recursive DFS
Write recursive DFS so it prints A B D C E F.
A B D C E Fconst graph = { A: ["B", "C"], B: ["A", "D"], C: ["A", "D", "E"], D: ["B", "C", "F"], E: ["C", "F"], F: ["D", "E"] };
const seen = new Set();
const order = [];
function dfs(u) {
// Mark u as seen, add it to order,
// then call dfs on each unseen neighbour.
}
dfs("A");
console.log(order.join(" "));
Hint
Add u to order when you arrive, before going deeper.
A solution
const graph = { A: ["B", "C"], B: ["A", "D"], C: ["A", "D", "E"], D: ["B", "C", "F"], E: ["C", "F"], F: ["D", "E"] };
const seen = new Set();
const order = [];
function dfs(u) {
seen.add(u);
order.push(u);
for (const v of graph[u]) {
if (!seen.has(v)) dfs(v);
}
}
dfs("A");
console.log(order.join(" "));17Explain
Common mistakes
const graph = { A: ["B"], B: ["A"] };
function dfs(u) {
for (const v of graph[u]) dfs(v);
}
dfs("A");RangeError: Maximum call stack size exceeded (line 3)
- The word before the colon names the kind of error: ReferenceError, TypeError, SyntaxError.
- After the colon: what went wrong, usually with the name involved.
- The line number shows where the program stopped. A SyntaxError stops it before any line runs.
Without a seen set the search goes A, B, A, B … forever, until the stack is full.
18
Summary
- A graph is vertices joined by edges; adjacency lists store it.
- BFS uses a queue, goes ring by ring, and finds fewest-edge paths.
- DFS uses a stack (or recursion), goes deep first, then backs up.
- Both run in O(V + E) and must remember seen vertices.
- Euler's 1736 Königsberg bridges solution began graph theory.