dfs.js
const graph = {
A: ["B", "C"],
B: ["D"],
C: ["E", "F"],
D: [],
E: [],
F: [],
};
function dfs(start) {
const stack = [start];
const visited = {};
const out = [];
while (stack.length > 0) {
const node = stack.pop();
if (visited[node]) continue;
visited[node] = true;
out.push(node);
const nbrs = graph[node];
for (let i = nbrs.length - 1; i >= 0; i--) {
stack.push(nbrs[i]);
}
}
return out;
}
dfs("A");
What to watch
Watch the stack grow and pop from the top; the graph node being visited lights up as the frontier deepens.
Reading dfs (graph + stack)on a page only gets you so far - code is a process, and the process happens at runtime where you can't normally see it. In NeonFlow, this exact program runs step by step: every call opens a frame, every branch picks a path, and every value moves through memory in front of you. That's the fastest way to actually understand how dfs (graph + stack) works.
Run dfs (graph + stack) yourself
Open NeonFlow, paste this code (or any of your own), and scrub through it one step at a time.
Open NeonFlow