Depth-First Search (DFS)
–
Pseudocode
1dfs(u):2 visited[u] ← true; visit(u)3 for each neighbour v of u:4 if not visited[v]:5 parent[v] ← u; dfs(v) // go deeper first6 return // backtrack to the caller
Visited
0
Edges checked
0
vertex being exploredstackon the call stackfinished / tree edge
What is Depth-First Search?
Depth-first search follows one path as deep as it can go. Only when a vertex has no unvisited neighbours left does it backtrack to the previous vertex and try its next option, like exploring a maze by always taking the next unexplored turn and walking back when you hit a dead end.
The recursion is a stack in disguise: the call stack on the right holds the path from the start to the current vertex. Every call is pushed when DFS goes deeper and popped when it backtracks. Compare it with BFS on the same graph to see how the visit order changes.
Go deep first, backtrack when stuck.
Using the Visualizer
- • Edit graph slides out the adjacency matrix: click a cell to add or remove an edge, or use Random / Example. Tick Directed for one-way edges.
- • Pick the start from the menu or click a vertex.
- • Blue vertices are still on the call stack (waiting for a deeper call to finish), green ones are finished. The # labels show the order each vertex was found.
- • Neighbours are tried in increasing order, so the result matches the code below.
Implementation
Properties & Complexity
Time Complexity
- • Adjacency list: O(V + E)
- • Adjacency matrix: O(V²)
- • Every vertex is entered once, every edge looked at once (twice if undirected)
Space & Properties
- • Space: O(V) for the call stack and arrays
- • Shortest paths: no, the first path found may be long
- • Order: one branch fully before the next
Where DFS Is Used
- • Mazes and puzzles: backtracking search
- • Cycle detection and finding connected parts
- • Topological sort: ordering tasks with dependencies
- • Tree traversals: pre-order, in-order, post-order are DFS
Limitations
- • Not shortest: use BFS for fewest edges
- • Deep graphs: recursion can overflow the call stack
- • Reachability: only finds vertices connected to the start