Graph - Depth First Search (DFS)
Walk a graph by following one path as deep as it goes, then stepping back to try the next one.
Given an undirected graph with vertices numbered 1 to nstartstart
Example 1
Output: [1, 2, 4, 3, 6, 5]
Example 2
Output: [4, 3, 5]
The Idea
Picture exploring a set of caves joined by tunnels, with a piece of chalk. You chalk every cave you enter. At each cave you take the first tunnel that leads to an unchalked cave, and you keep going. When a cave has no such tunnel, you walk back to the cave you came from and see if it has another one.
In Example 1 the caves are the six numbered circles, called vertices, and the tunnels are the edges, the lines between pairs of them. The walk starts at vertex 1, and the picture shows where it goes.
Follow the orange arrows by their numbers. Vertex 1 has two neighbours, 2 and 3, and the edge 1-2 comes first in the list, so move 1 goes to 2. From 2 the neighbours are 1, 4 and 5, and 1 is already chalked, so move 2 goes to 4. Move 3 goes from 4 to 3, and move 4 from 3 to 6.
Vertex 6 has one neighbour, 3, and it is already visited, so 6 is a dead end. The teal note at the bottom of the picture says what happens next. The walk steps back to 3 and finds nothing new, then back to 4, also with nothing new. Back at 2, vertex 5 is still unvisited, so move 5 goes there.
Look at the dashed line between 1 and 3. Vertex 3 sits right next to 1, yet the walk reached it the long way, through 2 and 4. By the time the walk is back at 1, 3 has been visited, so that edge is never used. The search goes as deep as it can along one path before it tries a second neighbour, and that is why it is called depth-first.
Two questions come out of this walk. How does the walk know where to step back to after a dead end? And what stops it from going round and round the loop 1, 2, 4, 3, back to 1? The steps back always return to the most recent vertex that is not finished yet: after 6, it was 3, then 4, then 2. So the unfinished vertices form a pile where the newest one is taken off first, which is called a stack. The chalk marks answer the second question.
Solution Approach
The code has to decide how to store the graph, how to chalk vertices, how to remember the way back, and what to do when a path is too long to remember that way.
Storing the graph as an adjacency list
How does the walk find the neighbours of a vertex? Scanning the whole edge list each time works, but then every one of the V visits reads all E edges, about V × E steps in all, where V is the number of vertices and E the number of edges.
It is cheaper to build, once, a list of neighbours for every vertex, called an adjacency list. For Example 1 it is 1: [2, 3], 2: [1, 4, 5], 3: [1, 4, 6], 4: [2, 3], 5: [2] and 6: [3]. The edge 4-3 puts 3 in the list of 4 and 4 in the list of 3, because the edges work both ways. Each list keeps the order of the edge list, so the walk tries the neighbours in the order the problem asks for.
Marking visited vertices
What plays the part of the chalk? A booleanvisited
Without the check, the walk never ends. A test run without it went 1, 2, 1, 2, 1, 2 and so on, because the edge 1-2 leads straight back each time, and it stopped with a StackOverflowError
Remembering the way back with recursion
Where is the stack of unfinished vertices kept? The shortest answer is to let Java keep it. A method visit(u)visitvisit(1)visit(2)visit(4)
Each of those calls waits, unfinished, until the deeper one returns. When visit(6)visit(3)
An explicit stack for very long paths
Is there a limit to how deep the calls can go? Each unfinished call takes room on the thread's call stack, and that room is fixed. Take a chain, a graph whose edges are 1-2, 2-3, 3-4 and so on. Starting at 1, every vertex is one call deeper than the last.
On our runs with Java 25 and its default settings, the recursive version handled a chain of 5,000 vertices, but threw StackOverflowErrorArrayDeque<Integer>
Two details decide whether this gives the same order as the recursion. First, the neighbours must be pushed from last to first, because the stack hands back the last one pushed first. Pushed in list order, Example 1 gives [1, 3, 6, 4, 2, 5]
Second, a vertex must be marked when it is popped, not when it is pushed. Marking on push gave [1, 2, 4, 5, 3, 6]
Java Solution
The method dfs
- First, the helper
turns the edge list into the adjacency listbuildGraph . It makes one emptyneighbours for each slot from 0 toArrayList , leaving slot 0 unused, and each edge adds both of its ends.n - Next,
createsdfs , avisited array ofboolean slots, all false, andn + 1 , an empty list for the result. Then it callsorder onvisit .start - The recursive method
setsvisit(u) to true and adds u tovisited[u] . Aorder loop then goes through the neighbours of u in list order. For each neighbour v that is not visited, it callsfor , and moves on to the next neighbour only after that call returns.visit(v) - When the first call to
returns, every vertex reachable fromvisit is instart , andorder returns that list.dfs
The class also holds dfsIterativeArrayDequemaindfsIterative
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
public class DepthFirstSearch {
// neighbours.get(u) lists every vertex joined to u, in the order the edges were given
static List<List<Integer>> buildGraph(int n, int[][] edges) {
List<List<Integer>> neighbours = new ArrayList<>();
for (int v = 0; v <= n; v++) {
neighbours.add(new ArrayList<>()); // slot 0 stays empty, vertices are 1..n
}
for (int[] e : edges) {
neighbours.get(e[0]).add(e[1]);
neighbours.get(e[1]).add(e[0]); // undirected: the edge works both ways
}
return neighbours;
}
public static List<Integer> dfs(int n, int[][] edges, int start) {
List<List<Integer>> neighbours = buildGraph(n, edges);
boolean[] visited = new boolean[n + 1];
List<Integer> order = new ArrayList<>();
visit(start, neighbours, visited, order);
return order;
}
private static void visit(int u, List<List<Integer>> neighbours,
boolean[] visited, List<Integer> order) {
visited[u] = true; // mark on arrival
order.add(u);
for (int v : neighbours.get(u)) {
if (!visited[v]) {
visit(v, neighbours, visited, order); // go deep before the next neighbour
}
}
} // returning here is the step back
public static List<Integer> dfsIterative(int n, int[][] edges, int start) {
List<List<Integer>> neighbours = buildGraph(n, edges);
boolean[] visited = new boolean[n + 1];
List<Integer> order = new ArrayList<>();
Deque<Integer> stack = new ArrayDeque<>();
stack.push(start);
while (!stack.isEmpty()) {
int u = stack.pop();
if (visited[u]) {
continue; // a second copy, pushed by another neighbour
}
visited[u] = true;
order.add(u);
List<Integer> next = neighbours.get(u);
for (int i = next.size() - 1; i >= 0; i--) { // last neighbour goes in first
if (!visited[next.get(i)]) {
stack.push(next.get(i));
}
}
}
return order;
}
public static void main(String[] args) {
int[][] example1 = {{1, 2}, {1, 3}, {2, 4}, {4, 3}, {2, 5}, {3, 6}};
System.out.println("Example 1, start 1: " + dfs(6, example1, 1));
int[][] example2 = {{1, 2}, {3, 4}, {4, 5}};
System.out.println("Example 2, start 4: " + dfs(5, example2, 4));
System.out.println("Example 1, start 6: " + dfs(6, example1, 6));
System.out.println("No edges, start 1: " + dfs(1, new int[0][], 1));
System.out.println("Stack version, Example 1: " + dfsIterative(6, example1, 1));
int n = 20001; // a chain 1-2, 2-3, ..., 20000-20001
int[][] chain = new int[n - 1][];
for (int v = 1; v < n; v++) {
chain[v - 1] = new int[] {v, v + 1};
}
try {
System.out.println("Chain, recursive: " + dfs(n, chain, 1).size() + " vertices");
} catch (StackOverflowError e) {
System.out.println("Chain, recursive: StackOverflowError");
}
int reached = dfsIterative(n, chain, 1).size();
System.out.println("Chain, stack version: " + reached + " vertices");
}
}
Running it prints:
Example 1, start 1: [1, 2, 4, 3, 6, 5]
Example 2, start 4: [4, 3, 5]
Example 1, start 6: [6, 3, 1, 2, 4, 5]
No edges, start 1: [1]
Stack version, Example 1: [1, 2, 4, 3, 6, 5]
Chain, recursive: StackOverflowError
Chain, stack version: 20001 vertices
The first line, [1, 2, 4, 3, 6, 5][4, 3, 5][6, 3, 1, 2, 4, 5]
A single vertex with no edges gives just [1]dfsIterative
Complexity
Each reachable vertex is visited once, and each visit reads that vertex's neighbour list once.
- Time: O(V + E), because building the lists handles each of the E edges twice, and the walk marks each of the V vertices once and reads its neighbour list, 2E entries in all.
- Space: O(V + E), because the adjacency list holds 2E entries, while
,visited and the chain of unfinishedorder calls each hold at most V items.visit - Stack version: O(E) for the stack, because each vertex can be pushed once by every neighbour that sees it unvisited. On a graph of 200 vertices all joined to each other, with 19,900 edges, the stack peaked at 19,702 entries.
The other basic way to walk a graph visits all neighbours of a vertex before going any deeper: see