Depth First Search or DFS for a Graph
You're given a graph as an adjacency list adj, where vertices are numbered 0 through V - 1 (with V = adj.length), and adj[i] lists the neighbors reachable directly from vertex i. Starting at vertex 0, perform a depth-first search (DFS) and return the sequence in which vertices are first reached (a preorder-style traversal).
Follow the standard DFS approach: fully explore one neighbor's branch before backtracking to try the next, visiting neighbors in the order they appear in each adjacency list as listed.
Sample Input and Output
Example 1 ยท Run Sample
adj = [[1,2],[3],[4],[],[]] [0,1,3,2,4] Example 2
adj = [[2,1],[0],[0]] [0,2,1] - 1 <= V <= 10^4
- 0 <= E <= 10^4
- Neighbors are visited in the listed order; vertices unreachable from 0 are omitted.
Test Cases (2)
Iterative DFS
Push neighbors in reverse order so they are visited in the original adjacency-list order. Mark a vertex when it is popped for its first visit; later duplicate stack entries are skipped.
function dfsOfGraph(adj) {
const visited=new Set(),stack=[0],result=[];
while(stack.length){const u=stack.pop();if(visited.has(u))continue;visited.add(u);result.push(u);for(let i=adj[u].length-1;i>=0;i--)if(!visited.has(adj[u][i]))stack.push(adj[u][i]);}
return result;
}Time: O(V + E) | Space: O(V + E)
Saved in this browser only. Private to you.