edubun
English
1 / 18

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 questions

You 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?"

A B C D E F

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);
Output
["A","D","E"]
3

4Explore

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.

ABCDEF
Queue (front on the left)
Visit order

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).

  1. D
  2. C
  3. A
  4. E
  5. F
  6. B
Hint

Distance 0, then 1, then 2, then 3 from A.

Solution

Answer:

  1. A
  2. B
  3. C
  4. D
  5. E
  6. 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.

ABCDEF
Call stack (top on the right)
Visit order

Visit A.

9Problem

DFS order

Put the vertices in the order recursive DFS from A visits them (neighbours in alphabetical order).

  1. E
  2. D
  3. C
  4. B
  5. F
  6. A
Hint

From D the first unseen neighbour is C.

Solution

Answer:

  1. A
  2. B
  3. D
  4. C
  5. E
  6. 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.

Expected output
A B C D E F
Your code
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 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.

Expected output
A B D C E F
Your code
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) {
  // 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");
Error message
RangeError: Maximum call stack size exceeded (line 3)
  1. The word before the colon names the kind of error: ReferenceError, TypeError, SyntaxError.
  2. After the colon: what went wrong, usually with the name involved.
  3. 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.

Back to the courseAlgorithms
Full text · The whole lesson as one text

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?"

BackgroundThe city of Königsberg (now Kaliningrad) had seven bridges linking two islands and the two banks of its river. People asked whether a walk could cross every bridge exactly once. In 1736 Leonhard Euler answered no. His key step was to throw away the map: only the land areas and the bridges between them mattered. Each land area became a point and each bridge a line. He then showed that such a walk needs every point, except possibly the start and the end, to have an even number of lines, and in Königsberg all four land areas had an odd number.
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.

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"],
};

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. From A in the example, BFS visits A, then B and C, then D and E, then F. Because it moves outward one ring at a time, the first time BFS reaches a vertex it has found a path with the fewest edges. F is 3 edges from A, for example A, B, D, F.

function bfs(graph, start) {
  const seen = new Set([start]);
  const queue = [start];
  const order = [];
  let head = 0;                     // index of the front of the queue
  while (head < queue.length) {
    const u = queue[head++];        // first in, first out
    order.push(u);
    for (const v of graph[u]) {
      if (!seen.has(v)) { seen.add(v); queue.push(v); }
    }
  }
  return order;   // A B C D E F
}

Depth-first search: as far as you can, then back up

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. From A, a recursive DFS visits A, B, D, C, E, F. DFS reaches every vertex BFS reaches, but the path it follows is not necessarily the shortest one.

function dfs(graph, u, seen = new Set(), order = []) {
  seen.add(u);
  order.push(u);
  for (const v of graph[u]) if (!seen.has(v)) dfs(graph, v, seen, order);
  return order;   // A B D C E F
}
A maze as a graph: each open square is a vertex, joined to the open squares next to it. Run BFS, then DFS on the same maze, and compare the squares visited and the length of the path found.

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. DFS also takes O(V + E) time, because it handles each vertex and edge a fixed number of times. Choose BFS when you need the fewest steps: the fewest moves in a puzzle, the fewest links between two people. Choose DFS when you need to explore everything or follow choices to the end. Examples are checking whether every room of a maze connects, or trying the moves of a puzzle one line at a time and backing up when stuck. When edges have different lengths, as roads do, neither is enough on its own; methods such as Dijkstra's algorithm extend the BFS idea with distances.

Both searches must remember which vertices they have already seen. Without that, a graph with a loop (A to B to D to C and back to A) would send the search round and round forever.
Key points
  • 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.

Practice questions from Graph search: BFS and DFS on edubun

Embed this quiz

Free to embed. Please keep the credit line.

Sources for this course (11)
  • MIT OpenCourseWare 6.006 Introduction to Algorithms, Spring 2020 (Demaine, Ku, Solomon)
  • lecture notes 1 Introduction, 3 Sorting, 9 Breadth-First Search, 10 Depth-First Search (ocw.mit.edu/courses/6-006-introduction-to-algorithms-spring-2020/pages/lecture-notes) and Fall 2011 lecture 13 BFS notes (ocw.mit.edu/courses/6-006-introduction-to-algorithms-fall-2011)
  • Cormen, Leiserson, Rivest, Stein, Introduction to Algorithms (MIT Press)
  • with the CLRS-based Khan Academy algorithms unit by Thomas Cormen and Devin Balkcom of Dartmouth (khanacademy.org/computing/computer-science/algorithms: binary search, selection sort analysis, merge sort, quicksort overview and analysis)
  • MacTutor History of Mathematics, Al-Khwarizmi (mathshistory.st-andrews.ac.uk/Biographies/Al-Khwarizmi: word algorithm from the Latin title Algoritmi de numero Indorum)
  • D. E. Joyce, Euclid's Elements Book VII Propositions 1 and 2 (mathcs.clarku.edu/~djoyce/elements/bookVII)
  • Wolfram MathWorld, Merge Sort (mathworld.wolfram.com/MergeSort.html: proposed by John von Neumann in 1945, after Knuth 1998 p. 159)
  • Stanford CS "Tony Hoare: Quicksort" (cs.stanford.edu/people/eroberts/courses/soco/projects/2008-09/tony-hoare/quicksort.html: devised while a student at Moscow State University for Russian-English machine translation with a tape dictionary, programmed in Algol 60 and published 1961; the year 1959 from the Wikipedia Quicksort article and its cited sources)
  • Bodleian Libraries, Ada Lovelace (blogs.bodleian.ox.ac.uk/adalovelace: 1843 paper, Note G Bernoulli numbers)
  • Fourmilab text of Menabrea's Sketch with Lovelace's notes (fourmilab.ch/babbage/sketch.html)
  • Seven Bridges of Konigsberg (Euler 1736) and Tower of Hanoi (Edouard Lucas, 1883) checked against the Wikipedia articles and their cited sources.

Checked: 2026-10-17