Depth-first search (DFS) is a graph traversal algorithm that follows one path as deep as it can, then backtracks to the nearest vertex with an unvisited neighbor and goes deep again, until it has visited every vertex it can reach. It keeps the way back on a stack and takes O(V + E) time with an adjacency list and O(V²) with an adjacency matrix. This page explains how it works, with a step-by-step animation of DFS on a tree from the VisiGrab app.
// how depth-first search works
Depth-first search (DFS) is a graph traversal algorithm: from a start vertex, it visits every vertex it can reach. It follows one path as deep as it can, to a dead end: a vertex whose neighbors, the vertices joined to it by an edge, have all been visited. Then it backtracks: it steps back along the path it came by and checks the vertices on it, the nearest first, for an unvisited neighbor. It does not visit them again; it only looks for a neighbor still to visit. From the first vertex that has one, it goes deep again. A stack, or recursion, remembers the way back. DFS takes O(V + E) time with an adjacency list and O(V2) with an adjacency matrix, for V vertices and E edges.
DFS marks each vertex visited when it reaches it, so none is explored twice. It keeps the vertices still being explored on a stack: push adds one on top, and pop removes the top one, the one pushed last. The app reads neighbors from the adjacency matrix: row B has a 1 in the column of each vertex joined to B. DFS visits the start vertex, A, and pushes it, then repeats three steps, shown on the app's default graph, a tree.
1. Go deeper: scan the top vertex's row from the left for the first 1 in an unvisited vertex's column. Visit that neighbor and push it. Here B is on top. Row B has 1s under A, D, E and F. A is visited, so the scan stops at D, which is visited and pushed.
2. Dead end: if the top vertex has no unvisited neighbor, pop it. Row D has a single 1, under B, which is visited. D is popped, and B is on top again.
3. Backtrack: scan the new top's row again from the left. Row B skips A and D, both visited, and stops at E, which is visited and pushed.
The steps repeat until a pop empties the stack. Each vertex is pushed once and popped once, and the stack always holds the path from the start to the top.
The iterative version keeps its own stack, as the app does, with names from the app's code. In pseudocode:
traverse(start)
stack = empty stack
visit(start)
stack.push(start)
while stack is not empty
u = stack.peek()
v = findUnvisitedNeighbor(u)
if v is none
stack.pop()
else
visit(v)
stack.push(v)
findUnvisitedNeighbor(u)
for v from 0 to V - 1
if matrix[u][v] == 1
if v is not visited
return v
return none
Vertices are numbered from 0. visit marks a vertex as visited, and peek reads the top without removing it. findUnvisitedNeighbor(u) scans row u from column 0 and returns the first v with matrix[u][v] == 1 that is not visited, or none, so the lowest index wins. Each pass of the while loop pushes or pops: V − 1 pushes and V pops, 17 passes for nine vertices.
The recursive version uses the call stack instead: each call goes on top of it, and each return removes it. In pseudocode:
recursiveDfs(u)
visit(u)
v = findUnvisitedNeighbor(u)
while v is not none
recursiveDfs(v)
v = findUnvisitedNeighbor(u)
recursiveDfs(u) visits u and calls itself on the first unvisited neighbor. After each call, u asks again, as the call may have visited some of u's other neighbors. When it gets none, the call returns: the pop. The calls still open are the vertices on the iterative stack, so both versions visit in the same order.
Many textbooks pop a vertex instead, visit it if still unvisited, and push all its unvisited neighbors: up to O(E) candidates, not the path. That version stops being a DFS if it marks vertices when they are pushed. On the edges A–B, A–C, A–D and B–D, with neighbors popped in alphabetical order, it visits A, B, C, D, not A, B, D, C. The app pushes one neighbor at a time, so it can mark on push.
The player below runs DFS from A on the app's default graph, a tree. It visits A, B, D, E, F, H, C, G, I, the tree's preorder. The dotted line leads from each visited vertex to the next one visited, so it also joins D to E, E to F and H to C, which share no edge.
Yes: an explicit stack takes the place of the call stack. The app's DFS runs this way: it pushes each vertex it visits, looks for an unvisited neighbor of the vertex on top and pops that vertex at a dead end, as the player shows. This iterative version visits the vertices in the same order as the recursive one, as the pseudocode explains.
Each vertex is pushed and popped once, so the time goes on finding neighbors. A matrix row has V cells however few edges there are, and each of the 2V − 1 scans reads at most V of them: O(V2). An adjacency list holds only real neighbors, 2E entries in an undirected graph. If each vertex's scan resumes where it stopped, as a for-each loop does inside a recursive call, every list is read once: O(V + E). Restarting each scan at the front, as findUnvisitedNeighbor above does, can cost O(V2) when one vertex is joined to all the others. Extra space is O(V): the visited marks and a stack of at most V vertices.
| Cost | Adjacency list | Adjacency matrix |
|---|---|---|
| Time | O(V + E) | O(V2) |
| Extra space | O(V) | O(V) |
| The graph itself | O(V + E) | O(V2) |
Breadth-first search (BFS) takes vertices from a queue, oldest first, so it spreads out level by level. Both take the same time, but only BFS finds the paths with the fewest edges in an unweighted graph. Full comparison →
On a directed graph DFS follows the arrows only. An arrow back to a vertex still on the stack is a back edge and closes a directed cycle. DFS there also meets forward edges, to a vertex further down its own branch, and cross edges, to a branch already finished. The postorder is the order in which DFS pops the vertices. With no cycle, the reversed postorder is a topological order: each vertex comes before the vertices its arrows lead to.
One DFS reaches only the start's connected component: the vertices that some path joins to it. To cover a disconnected graph, an outer loop starts a new DFS from each vertex still unvisited. Each start finds one component. The edges by which a DFS first reaches each vertex form its DFS tree, and the trees together form a DFS forest. The app's Graph Constructor runs one DFS, from the vertex you pick.
The app shows both versions in all three languages. Recursion nests one call per vertex on the path, so a long path can overflow the call stack.
Note
Python raises RecursionError after about 1,000 nested calls, its default recursion limit. Java throws StackOverflowError when the thread's stack runs out, and in C++ a stack overflow usually crashes the program.
An explicit stack avoids this. None of the three standard libraries has a graph DFS; NetworkX, JGraphT and the Boost Graph Library do.
The full source code is on GitHub, in Python, Java and C++.
// in the app
In VisiGrab DFS runs on four example graphs, beside the adjacency matrix and the stack, with a message for every visit and pop: 18 steps per graph.
The Examples dialog shows the four graphs as thumbnails. Besides the tree on this page, there are a graph with the cycle A–B–C–F–I–A, a tree of three chains hanging from A, and a ring of eight vertices with F inside it, joined to E; the app remembers your pick.
In the Graph Constructor, tap to place up to 12 vertices and drag between them to join them, tap Apply, then tap the vertex to start from and step through DFS with the traversal order listed. A switch runs BFS on the same graph.
Two tabs. Graph covers vertices, edges, adjacency, the kinds of graphs and both representations; DFS covers dead ends and backtracking, how the representation sets the visit order, four applications, and O(V + E) against O(V²) with pseudocode for each.
The iterative version with a stack, the Vertex class and the recursive version, with traverse, visit and findUnvisitedNeighbor in Java and find_unvisited_neighbor in Python and C++. A link opens the full source on GitHub, and after the last step a hint points to the code.
Ten questions with an explanation for every answer: four on graph basics, then six on DFS, from how it explores a graph to whether one graph can be traversed in two orders.
BFS has a topic of its own, with a queue where DFS has its stack, and so do Prim, Kruskal, Dijkstra, Bellman-Ford, topological sort and union-find.
// build your own
Download VisiGrab and step through DFS on four example graphs, or draw your own graph and start the search from any vertex.
Depth-first search is one of 30+ topics. See them all