01 / 21

Depth-First Search
DFS in Java

Learn to traverse graphs and trees by diving as deep as possible before backtracking: implement DFS with recursion and an explicit stack.

Computer Science Graph Algorithms Java

What Is a Graph?

A graph is a collection of nodes (vertices) connected by edges. Graphs model relationships: social networks, maps, web pages, and dependency chains. Before we search a graph, we need to understand its structure.

A B C D E F 6 nodes, 8 edges

What Is Depth-First Search?

DFS is a graph traversal strategy that explores as far as possible along each branch before backtracking. Think of walking through a maze: at every fork, you pick one path and keep going until you hit a dead end, then you retrace your steps.

Strategy
Go deep first, backtrack when stuck
Data Structure
Uses a stack (explicit or via recursion's call stack)
Time Complexity
\( O(V + E) \) where \( V \) = vertices, \( E \) = edges

Why Does DFS Matter?

DFS is a foundational algorithm that powers many real-world applications. Learning it gives you the building block for dozens of more advanced techniques.

1
Cycle detection: find loops in dependency graphs, deadlock detection.
2
Topological sorting: schedule tasks with prerequisites (build systems, course planning).
3
Pathfinding: maze solving, puzzle solving (Sudoku, N-Queens).
4
Connected components: determine if all nodes in a network are reachable.

The DFS Algorithm

1
Start at a chosen source node.
2
Mark the current node as visited.
3
For each unvisited neighbor, recursively call DFS on that neighbor.
4
Backtrack when no unvisited neighbors remain.

DFS Visual Walkthrough

0 1 2 3 4 5 1st 2nd 3rd 4th 5th 6th Visited (DFS path) Not yet visited

DFS vs BFS

DFS BFS
Strategy Go deep first Go wide first
Data structure Stack Queue
Memory \( O(h) \) (max depth) \( O(w) \) (max width)
Shortest path? Not guaranteed Yes (unweighted)
Best for Cycle detection, topological sort Shortest path, level-order

Representing Graphs in Java

We will use an adjacency list: an array (or List) where index \(i\) holds a list of neighbors of node \(i\). This is efficient for sparse graphs.

// Build an adjacency list for 6 nodes
List<List<Integer>> graph = new ArrayList<>();
for (int i = 0; i < 6; i++)
    graph.add(new ArrayList<>());

// Add undirected edges
graph.get(0).add(1);  graph.get(1).add(0);
graph.get(0).add(2);  graph.get(2).add(0);
graph.get(1).add(3);  graph.get(3).add(1);
graph.get(1).add(4);  graph.get(4).add(1);
graph.get(2).add(5);  graph.get(5).add(2);

How to Apply DFS

1
Build the graph: create an adjacency list from the input (edges, matrix, etc.).
2
Create a visited array: boolean[] visited = new boolean[n];
3
Choose your approach: recursive (cleaner) or iterative with an explicit stack (avoids stack overflow on deep graphs).
4
Call DFS from the starting node. If the graph may be disconnected, loop over all nodes and call DFS on each unvisited one.
5
Process results: collect traversal order, detect cycles, or compute connected components.

Recursive DFS in Java

static void dfs(List<List<Integer>> graph,
                 int node,
                 boolean[] visited) {
    visited[node] = true;
    System.out.print(node + " ");

    for (int neighbor : graph.get(node)) {
        if (!visited[neighbor]) {
            dfs(graph, neighbor, visited);
        }
    }
}

Tracing the Recursive Calls

Using the 6-node graph from earlier, starting at node 0:

Step Call Action Call Stack
1 dfs(0) Visit 0, go to neighbor 1 [0]
2 dfs(1) Visit 1, go to neighbor 3 [0, 1]
3 dfs(3) Visit 3, no unvisited neighbors [0, 1, 3]
4 backtrack Return to 1, go to neighbor 4 [0, 1]
5 dfs(4) Visit 4, no unvisited neighbors [0, 1, 4]
6 backtrack Return to 0, go to neighbor 2 [0]
7 dfs(2) Visit 2, go to neighbor 5 [0, 2]
8 dfs(5) Visit 5, done [0, 2, 5]

Iterative DFS with an Explicit Stack

static void dfsIterative(List<List<Integer>> graph,
                          int start) {
    boolean[] visited = new boolean[graph.size()];
    Stack<Integer> stack = new Stack<>();
    stack.push(start);

    while (!stack.isEmpty()) {
        int node = stack.pop();
        if (visited[node]) continue;
        visited[node] = true;
        System.out.print(node + " ");

        // Push neighbors in reverse for same order
        List<Integer> nbrs = graph.get(node);
        for (int i = nbrs.size() - 1; i >= 0; i--) {
            if (!visited[nbrs.get(i)])
                stack.push(nbrs.get(i));
        }
    }
}

Example: Connected Components

Use DFS to count how many connected components exist in an undirected graph. Loop over all nodes: if a node is unvisited, start a new DFS and increment the count.

static int countComponents(int n,
        List<List<Integer>> graph) {
    boolean[] visited = new boolean[n];
    int count = 0;

    for (int i = 0; i < n; i++) {
        if (!visited[i]) {
            dfs(graph, i, visited);
            count++;
        }
    }
    return count;
}
0 1 2 Component 1 3 4 Component 2 5 Component 3

Example: Cycle Detection

In an undirected graph, a cycle exists if during DFS you encounter a visited node that is not the parent of the current node.

static boolean hasCycle(List<List<Integer>> graph,
        int node, int parent, boolean[] visited) {
    visited[node] = true;

    for (int neighbor : graph.get(node)) {
        if (!visited[neighbor]) {
            if (hasCycle(graph, neighbor, node, visited))
                return true;
        } else if (neighbor != parent) {
            return true; // back edge found
        }
    }
    return false;
}

Common Mistakes

✕ Forgetting the visited check
Without checking visited[node], DFS will loop infinitely on graphs with cycles.
✕ Not handling disconnected graphs
A single DFS call only reaches nodes connected to the start. Loop over all nodes to cover the entire graph.
✕ Ignoring duplicate pushes
In iterative DFS, the same node can be pushed onto the stack multiple times. Always check visited when popping (or before pushing) to avoid redundant work.

DFS at a Glance

Recursive DFS Iterative DFS
Stack Implicit (call stack) Explicit (java.util.Stack)
Code length Shorter, cleaner Longer, more control
Deep graphs StackOverflowError risk Safe (heap memory)
Time complexity \( O(V + E) \) \( O(V + E) \)
Space complexity \( O(h) \) (max depth) \( O(V) \) (worst case)
Best for Small to medium graphs Very deep or large graphs

Question 1 of 5

What data structure does DFS use implicitly in its recursive implementation?

Question 2 of 5

What is the time complexity of DFS on a graph with \( V \) vertices and \( E \) edges?

Question 3 of 5

Given this adjacency list (neighbors listed in order), what is the DFS traversal starting at node A?
A: [B, C]   B: [A, D]   C: [A]   D: [B]

Question 4 of 5

In the iterative DFS implementation shown in this lesson, why do we push neighbors in reverse order?

Question 5 of 5

What happens if you run DFS on a graph with cycles without a visited array?