Lesson 2 · Unit 02
Depth-first search
Go deep, back up at dead ends
What you practise
- Recursive and with an explicit stack
- Reachability
Try a question from this lesson
Pick one
You explore a maze by always taking a corridor you have not tried, and backing up only at dead ends. What must you remember to back up correctly?
Correct answer
The rooms on your way here, most recent first
Why
Backing up undoes your most recent step first: last in, first out. That is a stack, and "go deep, back up at dead ends" is depth-first search.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
DFS by recursion
Depth-first search fits in a few lines when a function calls itself: mark the node, then visit each neighbour that is not marked yet.
The call stack does the remembering. When a call runs out of neighbours it returns, which is the backing up.
adj = [[1, 2], [0, 3], [0], [1]]
seen = set()
def dfs(node):
seen.add(node)
print(node)
for nxt in adj[node]:
if nxt not in seen:
dfs(nxt)
dfs(0) # prints 0 1 3 2const adj = [[1, 2], [0, 3], [0], [1]];
const seen = new Set();
function dfs(node) {
seen.add(node);
console.log(node);
for (const nxt of adj[node]) {
if (!seen.has(nxt)) dfs(nxt);
}
}
dfs(0); // prints 0 1 3 2const adj = [[1, 2], [0, 3], [0], [1]];
const seen = new Set<number>();
function dfs(node: number): void {
seen.add(node);
console.log(node);
for (const nxt of adj[node]) {
if (!seen.has(nxt)) dfs(nxt);
}
}
dfs(0); // prints 0 1 3 2TypeScript note: void says the function returns nothing: it is called for its effect on seen.
Concept
DFS with your own stack
Swap the queue of a breadth-first search for a stack and it becomes depth-first: the node explored next is the one discovered most recently.
No recursion means no limit on depth except memory.
def reachable(adj, start):
seen = {start}
stack = [start]
while stack:
node = stack.pop()
for nxt in adj[node]:
if nxt not in seen:
seen.add(nxt)
stack.append(nxt)
return seenfunction reachable(adj, start) {
const seen = new Set([start]);
const stack = [start];
while (stack.length > 0) {
const node = stack.pop();
for (const nxt of adj[node]) {
if (seen.has(nxt)) continue;
seen.add(nxt);
stack.push(nxt);
}
}
return seen;
}function reachable(
adj: number[][], start: number,
): Set<number> {
const seen = new Set([start]);
const stack = [start];
while (stack.length > 0) {
const node = stack.pop()!;
for (const nxt of adj[node]) {
if (seen.has(nxt)) continue;
seen.add(nxt);
stack.push(nxt);
}
}
return seen;
}TypeScript notestack.pop() has type number | undefined. The ! tells the compiler it cannot be undefined here, because the loop only runs while the stack has items.
8 more exercises in the app
- 3× multiple choice
- 1× order the lines
- 1× true or false
- 1× fill the blanks
- 1× match the pairs
- 1× type the answer
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.