1. Stack
DFS uses a stack to explore the most recent node first.
const stack = [start]Typorithm · medium
Step 1 of 8 · intro card
Search Algorithms
Depth-First Search explores a graph by going deep along one path before backtracking.
DFS uses a stack to choose the most recently discovered node.
It can be implemented recursively or iteratively; this lesson uses a stack.
A visited set prevents cycles from causing repeated work.
DFS is useful for reachability, connected components, and backtracking-style exploration.
Use a stack.
Pop the newest node.
Skip already visited nodes.
Push neighbors to go deeper.
Time is O(V + E).
function depthFirstSearch(graph, start, target) {
const stack = [start];
const visited = new Set();
while (stack.length > 0) {
const node = stack.pop();
if (visited.has(node)) continue;
visited.add(node);
if (node === target) return true;
for (const neighbor of graph[node] ?? []) {
stack.push(neighbor);
}
}
return false;
}Connect each part of the code to the concept before you type.
DFS uses a stack to explore the most recent node first.
const stack = [start]visited prevents repeated processing.
const visited = new Set()Keep going while there are nodes to explore.
while (stack.length > 0)Take the newest discovered node.
const node = stack.pop()Avoid processing a node twice.
if (visited.has(node)) continueReturn true when DFS reaches the target.
if (node === target) return trueNeighbors are pushed for later depth-first exploration.
stack.push(neighbor)Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputUndirected graph · start A · edges A–B:4, A–D:2, B–C:3, B–E:1, D–E:5, E–F:2, C–F:4
Follow temporary values, local state and supporting structures at this step.
No temporary values have been saved in this frame yet.
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state