← All coursesDSA Foundations

Lesson 16 of 19

Depth-first search

Walk through connected rooms. Mark each room when you enter it. Take the first doorway to an unseen room, then retrace your steps when you run out of new doorways.

Return to the room that still has work

A recursive visit remembers which doorway to try next. Mark a room on entry so that a cycle cannot send you around again. A return to an earlier room continues its unfinished visit.

Work through an example

Four rooms have two-way doors A–B, A–C, A–D and B–D. Starting at A and trying neighbors alphabetically, in what order do you first enter the rooms?

Step-by-step solution
  1. Mark A, then choose B, its first unseen neighbor. In B, the door to A leads to a marked room, so enter D.
  2. Both doors from D lead to marked rooms. Return to B, finish its list and return to A.
  3. C is the next unseen neighbor of A. The last door from A leads to D, which already has a mark. The visit order is A, B, D, C.
JavaScript example
const doors = { A: ["B", "C", "D"], B: ["A", "D"], C: ["A"], D: ["A", "B"] };
const seen = new Set();
const order = [];

function visit(room) {
  seen.add(room);
  order.push(room);
  for (const neighbor of doors[room]) {
    if (!seen.has(neighbor)) visit(neighbor);
  }
}

visit("A");
order;
DSA compiler

Try it yourself

Finish the animation to unlock this question.

You reached D from B. Every neighbor of D has been visited. Where does the search resume?

Related exercise · Depth-first search on a graph · See this stage of the beginner path