To traverse a graph is to visit its vertices in a systematic order, for example to search for a vertex or to find everything reachable from a starting point. Because graphs can contain cycles, a traversal must remember which vertices it has already visited.
There are two standard graph traversals:
Breadth First Search (BFS)
- Depth First Search (DFS)
This tutorial covers Depth First Search.
What is the Depth First Search (DFS) Algorithm?
Depth First Search explores a graph by following one path as far as it can go. From the current vertex it moves to an unvisited neighbour, then to an unvisited neighbour of that vertex, and so on. When it reaches a vertex with no unvisited neighbours (a dead end), it backtracks to the most recent vertex that still has unvisited neighbours and continues from there.
DFS is naturally written with recursion, where the call stack remembers the path back; an iterative version uses an explicit stack instead.
How the DFS algorithm works
- Start: mark the starting vertex as visited and process it.
- Go deeper: pick an unvisited neighbour of the current vertex and repeat the same steps from it.
- Backtrack: when the current vertex has no unvisited neighbours left, return to the vertex you came from and try its next unvisited neighbour.
- Finish: the search ends when the starting vertex has no unvisited neighbours left (or as soon as a target vertex is found). To cover a disconnected graph, start a new DFS from every vertex that is still unvisited.
Example of DFS (Depth First Search)
import java.util.ArrayList;
import java.util.List;
// Recursive depth-first search on a directed graph stored as an adjacency list
public class DFSExample {
private final List<List<Integer>> graph = new ArrayList<>();
private final boolean[] visited;
DFSExample(int vertices) {
visited = new boolean[vertices];
for (int i = 0; i < vertices; i++) {
graph.add(new ArrayList<>());
}
}
// Directed edge: from -> to
void addEdge(int from, int to) {
graph.get(from).add(to);
}
// Visit a vertex, then go as deep as possible through each unvisited neighbour
void dfs(int vertex) {
visited[vertex] = true;
System.out.print(vertex + " ");
for (int next : graph.get(vertex)) {
if (!visited[next]) {
dfs(next); // go deeper; when this returns, we have backtracked
}
}
}
public static void main(String[] args) {
// 0
// / \
// 1 2
// | |
// 3 4
DFSExample g = new DFSExample(5);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 3);
g.addEdge(2, 4);
System.out.println("Following is Depth First Traversal (DFS):");
g.dfs(0);
System.out.println();
}
}
Following is Depth First Traversal (DFS): 0 1 3 2 4
From 0 the search goes to 1 and then deeper to 3. Vertex 3 is a dead end, so it backtracks through 1 to 0 and continues with 0's next neighbour, 2, and then 4. The visiting order is 0, 1, 3, 2, 4.
Time Complexity of DFS Algorithm
With an adjacency list, DFS takes O(V + E) time, where V is the number of vertices and E the number of edges: each vertex is visited once and each adjacency list is scanned once. With an adjacency matrix it takes O(V2).
Space Complexity of DFS Algorithm
DFS needs O(V) extra space: the visited array plus the recursion (or explicit) stack, which can grow as deep as the longest path explored, up to V vertices. In Java, very deep recursion can cause a StackOverflowError, so large graphs are often searched with an explicit stack.
Applications of the DFS Algorithm
- Reachability and paths: finding whether one vertex can be reached from another and returning a path (not necessarily the shortest; use BFS for that in unweighted graphs).
- Cycle detection: in a directed graph, an edge to a vertex that is still on the current path (a back edge) means there is a cycle.
- Topological sorting: listing the vertices of a DAG in reverse order of DFS finishing time gives a valid order for dependencies and build steps.
- Connected components: each new DFS started from an unvisited vertex discovers one component of an undirected graph.
- Backtracking puzzles: Sudoku, N-Queens and maze generation explore choices depth-first and undo them on dead ends.
- Strongly connected components and bridges: algorithms such as Tarjan's and Kosaraju's are built on DFS.