DFS of Graph
Return the depth-first traversal order of a graph given as an adjacency list.
Open on GeeksforGeeks ↗Intuition
DFS commits to one path and follows it as far as it goes before backing up. The only bookkeeping needed is a visited set — without it any cycle sends the traversal round forever. Mark a vertex the moment you arrive, not when you leave, so a neighbour can never queue it a second time.
Approach
Recurse, marking on arrival
dfs(v): mark v visited, record it, then recurse into every unvisited neighbour. Marking before recursing is what makes cycles safe — a neighbour that loops back finds v already marked and stops.
Handle disconnected graphs
A single dfs(0) only reaches vertices connected to 0. Loop over all vertices and start a fresh DFS from each unvisited one, so every component is covered.
Recursion or explicit stack
The call stack is doing the work of a stack; swapping in an explicit list gives the same order (push neighbours in reverse to match) and avoids stack-overflow on deep graphs.
Solution & live demo
Edge cases
Outer loop restarts DFS at every unvisited vertex.
The vertex is already marked when the loop edge is examined — skipped.
Visited and recorded with no recursion.