Depth-first search
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Depth-first search explores a graph by diving as deep as possible along each branch before backtracking.
Recursive DFS and call stack execution
Depth-first search (DFS) explores a graph by going as deep as possible along each path before backtracking, using recursion or a stack.
Depth-first search behaves like walking through a maze, following one corridor until reaching a dead end. When a path cannot continue, it backtracks to the previous junction to explore untried corridors. This makes recursion the most natural implementation of DFS.
DFS dives deeply before backtracking
Step 1 of 5
Example 1 · Recursive Depth-First Search in Java
import java.util.*;
public class Main { static void dfs(int u, List<List<Integer>> adj, boolean[] visited) { visited[u] = true; System.out.print(u + " ");
for (int v : adj.get(u)) { if (!visited[v]) { dfs(v, adj, visited); } } }
public static void main(String[] args) { int n = 4; List<List<Integer>> adj = new ArrayList<>(); for (int i = 0; i < n; i++) adj.add(new ArrayList<>()); adj.get(0).addAll(Arrays.asList(1, 3)); adj.get(1).addAll(Arrays.asList(0, 2)); adj.get(2).addAll(Arrays.asList(1)); adj.get(3).addAll(Arrays.asList(0));
boolean[] visited = new boolean[n]; System.out.print("DFS order: "); dfs(0, adj, visited); System.out.println(); }}DFS order: 0 1 2 3
What this code does
- DFS starts at node 0 and dives down to neighbour 1, then to neighbour 2.
- When node 2 has no more unvisited neighbours, it backtracks to 0.
- Finally, node 0 visits its remaining neighbour 3.
Example 2 · Finding Any Path Between Two Nodes Using DFS
import java.util.*;
public class Main { static boolean findPath(int u, int target, List<List<Integer>> adj, boolean[] vis, List<Integer> path) { vis[u] = true; path.add(u); if (u == target) return true;
for (int v : adj.get(u)) { if (!vis[v]) { if (findPath(v, target, adj, vis, path)) return true; } }
path.remove(path.size() - 1); // Backtrack return false; }
public static void main(String[] args) { int n = 5; List<List<Integer>> adj = new ArrayList<>(); for (int i = 0; i < n; i++) adj.add(new ArrayList<>()); adj.get(0).add(1); adj.get(1).addAll(Arrays.asList(0, 2)); adj.get(2).addAll(Arrays.asList(1, 4)); adj.get(4).add(2);
List<Integer> path = new ArrayList<>(); findPath(0, 4, adj, new boolean[n], path); System.out.println("Path 0 to 4: " + path); }}Path 0 to 4: [0, 1, 2, 4]
What this code does
- path accumulates nodes along the active recursive call branch.
- If target is found, returns true immediately without undoing steps.
- If a branch fails, path removes the last node during backtracking.
The Java call stack keeps track of the active traversal path automatically. When visiting node u, mark visited[u] true. Iterate through all neighbours of u, calling dfs recursively on each unvisited neighbour. When a recursive call finishes, execution returns to node u, naturally backtracking along the tree branch.
Iterative DFS using an explicit stack
Very deep graphs can cause recursive DFS to fail with a StackOverflowError. When graphs form long chains of thousands of vertices, call stack depth exceeds default limits. An iterative implementation uses an explicit heap-allocated Deque or Stack in Java.
Example 3 · Iterative DFS Using an Explicit Stack
import java.util.*;
public class Main { static void dfsIterative(int start, List<List<Integer>> adj, int n) { boolean[] visited = new boolean[n]; Deque<Integer> stack = new ArrayDeque<>(); stack.push(start);
System.out.print("Iterative DFS: "); while (!stack.isEmpty()) { int u = stack.pop(); if (!visited[u]) { visited[u] = true; System.out.print(u + " ");
// Push neighbors in reverse to match recursive order List<Integer> neighbors = adj.get(u); for (int i = neighbors.size() - 1; i >= 0; i--) { int v = neighbors.get(i); if (!visited[v]) stack.push(v); } } } System.out.println(); }
public static void main(String[] args) { int n = 4; List<List<Integer>> adj = new ArrayList<>(); for (int i = 0; i < n; i++) adj.add(new ArrayList<>()); adj.get(0).addAll(Arrays.asList(1, 3)); adj.get(1).addAll(Arrays.asList(0, 2)); adj.get(2).add(1); adj.get(3).add(0);
dfsIterative(0, adj, n); }}Iterative DFS: 0 1 2 3
What this code does
- ArrayDeque acts as an explicit LIFO stack on heap memory.
- Neighbours pushed in reverse order ensure leftmost neighbour is popped first.
- Avoids deep call stack frames that trigger stack overflow.
Push the starting vertex onto the stack. While the stack is not empty, pop the top element. If the element was not previously visited, mark it visited and push all its unvisited neighbours. Because explicit stacks reside on heap memory, they support traversals across massive graph structures safely.
Predict the output
Predict the order
A stack gives DFS order and a queue gives BFS order. Pick what each snippet prints.
Round 1 of 3
Comparing BFS and DFS characteristics
BFS uses a queue and visits vertices level by level in order of shortest distance. DFS uses a stack and drives deeply along single paths before backtracking.
Deque<Integer> queue = new ArrayDeque<>();queue.offer(start);int bfsNext = queue.poll(); // BFS: oldest vertex first (FIFO)
Deque<Integer> stack = new ArrayDeque<>();stack.push(start);int dfsNext = stack.pop(); // DFS: newest vertex first (LIFO)Both algorithms run in linear O(V + E) time on adjacency lists and require O(V) memory. Use BFS when seeking the shortest path in unweighted graphs or minimum moves in puzzles. Use DFS for topological sorting, cycle detection, connected components, and exhaustive maze explorations.
Next step
Check your understanding
10 quick questions