CS 360: Data Structures and Algorithms
DFS Algorithm
Depth-First Search in Graphs:
DFS is most similar to pre-order traversal of a tree,
and can also be similar to post-order traversal
boolean seen[1…n];
DFS (Graph G) {
for (k = 1; k<=n; k++)
seen[k] = false;
choose start vertex;
DFS (G, start);
}
DFS (G, x) {
seen[x] = true;
preVisit (x);
// visits nodes in DFS order or pre-order
for each vertex y such that (x,y) is an edge
if (! seen[y]) {
// optionally add edge (x,y) to the DFS tree;
DFS (G, y);
}
postVisit (x);
// optional, visits nodes in post-order
}
Example: Undirected Graph
1
2
3
4
5
6
7
8
9
DFS starting at vertex 1:
DFS starting at vertex 8:
1
8
2
5
3
6
5
4
7
2
1
3
8
4
6
9
7
9
DFS order: 1,2,3,6,5,4,7,8,9
DFS order: 8,5,2,1,4,7,3,6,9
(DFS order is the same as pre-order of the DFS tree)
Example: Directed Graph
1
2
3
4
5
6
7
8
9
DFS starting at vertex 5:
DFS starting at vertex 8:
5
8
2
4
1
3
4
6
9
2
1
8
7
7
3
6
9
DFS order: 5,2,1,4,3,6,8,7,9
5
DFS order: 8,4,2,1,3,6,5,7,9
(DFS order is the same as pre-order of the DFS tree)
Analysis of DFS (same as for BFS):
If graph represented using adjacency matrix:
θ(n2) time
If graph represented using adjacency lists:
θ(n+m) time
Simplifies to θ(m) time if graph is connected,
because m ≥ n–1 for connected graphs
Note: it is more efficient to use adjacency lists,
because m ≤ n2 for all graphs
Applications of DFS:
• Connectedness of undirected graph (same as for BFS):
Is the graph connected?
If not, find all the connected components
start
start
1
2
3
4
5
6
7
8
9
start
Components: {1,2,4,5} {3,6} {7,8,9}
More applications of DFS (we’ll discuss these next time):
• Strong connectedness of directed graph:
Is the graph strongly connected?
If not, find all the strongly connected components
• Detecting a cycle (in undirected or directed graph)
• Topological sort of a Directed Acyclic Graph:
a linear ordering of the vertices so that whenever
edge x→y exists, vertex x must precede vertex y
© Copyright 2026 Paperzz