Lesson 21 of 30
Depth-first and breadth-first search both work on graphs almost unchanged — except for one new habit graphs force on you that trees never did: remembering where you've already been.
11 min read
Every option explains itself — why the right one is right, and why each wrong one is wrong. Miss one and it comes back later on a spaced-repetition schedule.
This topic is about judgment and practical tradeoffs more than a single right answer — a mock interview is the better way to test yourself on it.
Be interviewed on this →Hints without spoilers, and a plain explanation of why a wrong answer was wrong — answered only from this lesson. Free account, no card.
Sign up freeWhat interviewers actually ask about this, and what a strong answer has to cover.
A strong answer covers
Likely follow-ups
You already know how to explore a tree two ways: diving deep down one path (depth-first), or spreading out ring by ring (breadth-first). Good news — both work on graphs too, with almost no changes.
Here's the catch a tree never gave you. In a maze shaped like a tree, every hallway leads somewhere new — you can never accidentally walk in a circle. A graph doesn't make that promise. Picture an actual maze with loops in it: walk far enough and you can end up back at a hallway you already explored, walking it again, without realizing you're going in circles.
So graph traversal needs one new habit that tree traversal never needed: leaving a mark. Before you walk into a hallway, note that you've already been there. If you reach a hallway you've already marked, turn back — you already know what's down there.
This single idea — remembering where you've been — is the entire difference between traversing a tree and traversing a graph. Everything else about depth-first and breadth-first search stays exactly the same.
const maze = {
entrance: ["hallwayA", "hallwayB"],
hallwayA: ["entrance", "junction"], // loops back to the entrance!
hallwayB: ["junction"],
junction: ["hallwayA", "hallwayB", "exit"],
exit: [],
};
function findPath(start) {
const visited = new Set(); // rooms we've already seen
const queue = [start];
visited.add(start);
while (queue.length > 0) {
const room = queue.shift();
console.log("visiting:", room);
for (const next of maze[room]) {
if (!visited.has(next)) {
visited.add(next); // mark it the moment we discover it
queue.push(next);
}
}
}
}
findPath("entrance"); // visits each room exactly once, even with the loop
This lesson combines the depth-first and breadth-first traversal from the previous lesson with the graph structure from the lesson before that, plus one new addition they need together: a way to remember where you've been.