1. Visited set
Track nodes already explored to avoid infinite loops on cycles.
const visited = new Set()Typorithm · medium
Step 1 of 8 · intro card
Graph Algorithms
Follow one path as deep as possible, backtracking when stuck, using a visited set against cycles.
DFS commits to a neighbor and explores it fully before trying the next one.
A visited set is essential — without it, a cycle would loop forever.
Recursion naturally implements the dive-and-backtrack behavior via the call stack.
Mark visited on entry.
Recurse into unseen neighbors.
The call stack does the backtracking.
function dfs(graph, start) {
const visited = new Set();
const order = [];
function explore(node) {
visited.add(node);
order.push(node);
for (const next of graph[node]) {
if (!visited.has(next)) {
explore(next);
}
}
}
explore(start);
return order;
}Connect each part of the code to the concept before you type.
Track nodes already explored to avoid infinite loops on cycles.
const visited = new Set()Mark a node visited as soon as exploration begins.
visited.add(node)Follow each unseen neighbor all the way down before backtracking.
explore(next)Only recurse into neighbors not yet seen.
if (!visited.has(next))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