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 n, its edges as a list of pairs, and a start vertex, list the vertices in the order depth-first search (DFS) visits them. From each vertex, the search moves on to the first neighbour it has not visited yet, and steps back only when there is none left. Try the neighbours of a vertex in the order its edges appear in the list. Vertices that cannot be reached from start are left out.

Example 1
Input: n = 6, edges = [[1, 2], [1, 3], [2, 4], [4, 3], [2, 5], [3, 6]], start = 1
Output: [1, 2, 4, 3, 6, 5]
Example 2
Input: n = 5, edges = [[1, 2], [3, 4], [4, 5]], start = 4
Output: [4, 3, 5]
Solution

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.

The graph of Example 1 with vertices 1 to 6. Orange arrows show the moves 1 to 2, 2 to 4, 4 to 3, 3 to 6 and 2 to 5. The dashed edge 1-3 is not used because 3 is already visited. Visit order: 1, 2, 4, 3, 6, 5.

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 boolean array, visited, with one slot per vertex. A vertex is marked the moment the walk arrives, and the walk never moves to a marked vertex. In Example 1 that is what keeps 3 from leading back to 1, and 6 from leading back to 3.

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 after a few thousand calls.

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) marks u, then goes through its neighbours, and for an unvisited one calls visit again. In Example 1, visit(1) calls visit(2), which calls visit(4), so the method calls itself; that is recursion.

Each of those calls waits, unfinished, until the deeper one returns. When visit(6) finds no new neighbour and returns, Java goes back into visit(3) at the point where it left off. That return is the step back, and Java's own call stack remembers the way.

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 StackOverflowError on chains of 10,000 and 20,001 vertices. The fix is to keep the stack yourself, in an ArrayDeque<Integer> of vertices waiting to be visited. The loop pops a vertex, skips it if it is already marked, and otherwise marks it, records it, and pushes its unvisited neighbours.

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]. That is still a depth-first walk, but it tries each vertex's neighbours from the end of its list.

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] for Example 1, which is not depth-first at all. Vertex 1 pushed 3 and marked it, so at 4 the walk could not go on to 3, and it fell back to 5 instead. Marking on pop lets a vertex sit on the stack more than once, and the skip check handles the extra copies.

Java Solution

The method dfs works in these steps:

  1. First, the helper buildGraph turns the edge list into the adjacency list neighbours. It makes one empty ArrayList for each slot from 0 to n, leaving slot 0 unused, and each edge adds both of its ends.
  2. Next, dfs creates visited, a boolean array of n + 1 slots, all false, and order, an empty list for the result. Then it calls visit on start.
  3. The recursive method visit(u) sets visited[u] to true and adds u to order. A for loop then goes through the neighbours of u in list order. For each neighbour v that is not visited, it calls visit(v), and moves on to the next neighbour only after that call returns.
  4. When the first call to visit returns, every vertex reachable from start is in order, and dfs returns that list.

The class also holds dfsIterative, the version with an ArrayDeque as its stack, which marks on pop and pushes neighbours from last to first. The main method runs both examples, Example 1 again from vertex 6, one vertex with no edges, dfsIterative on Example 1, and both versions on a chain of 20,001 vertices.

Java
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:

Output
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], is the walk in the picture. The second, [4, 3, 5], leaves out 1 and 2, because no edge joins them to 4, 3 or 5. The third line runs Example 1 from 6 and gets [6, 3, 1, 2, 4, 5]. From 6 the walk has to go to 3, and 3 now tries 1 first, so this time the edge 1-3 is used and 4 is reached from 2.

A single vertex with no edges gives just [1]. The line for dfsIterative matches the first line exactly, which is what the reversed push and the marking on pop are for. The last two lines are the long chain: the recursive version runs out of call stack, while the stack version reaches all 20,001 vertices.

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, order and the chain of unfinished visit calls each hold at most V items.
  • 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 Breadth First Search (BFS).