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.
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.
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.
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.
The DFS Algorithm
DFS Visual Walkthrough
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
boolean[] visited = new boolean[n];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; }
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
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?