Concepts

Depth-first search preorder

Try the free JavaScript compiler

Explore outgoing edges depth-first with visited state. For large graphs use explicit stack frames to avoid call-stack limitations; a single start covers only reachable vertices.

Formal Syntax & Structure

javascript syntaxjavascript
dfs(vertex) { mark(vertex); visit unmarked neighbors; }

Working Example

Example Snippetjavascript
const adj=[[1,2],[3],[],[0],[]],seen=new Set(),out=[];function dfs(u){if(seen.has(u))return;seen.add(u);out.push(u);for(const v of adj[u])dfs(v);}dfs(0);console.log(JSON.stringify(out));
JavaScript Reference