DFS
Depth-first search explores as far as possible along one branch before it backtracks. You implement it with recursion or an explicit stack. It finds cycles, components, and paths; it does not find unweighted shortest paths.
Detailed Explanation
BFS uses a queue and expands by distance. DFS uses a stack and expands by depth. Recursion is that stack. You enter a node, mark it, and recurse on each unseen neighbour. When a call returns, you try the next neighbour. The order depends on how neighbours are stored.
DFS is the right shape for "can I finish this path?", for cycle detection in a directed graph (three colours: unvisited, on the stack, done), for topological sort, for connected components, and for flood fill. It is the wrong shape for fewest hops; the first time you reach a node may be a long path.
Java's call stack is finite. A line-shaped graph of 10_000 nodes can throw StackOverflowError. Convert to an explicit ArrayDeque stack, or raise stack size only as a last resort. Mark visited when you push, the same as BFS, if you use an explicit stack and do not want duplicates on it.
On a directed graph, "visited" is not enough to detect a cycle: a node can be finished and still be a neighbour of a new node. Keep an "on recursion stack" flag. A back edge to a node on the stack is a cycle.
You reach for recursive DFS when the graph is small and the code is a search with extra state per frame (backtracking). You reach for iterative DFS when depth is unknown. You reach for BFS when the metric is hops.
The cost is O(V + E) time. Extra memory is the depth of the search, which can be O(V). Tree DFS can compute subtree answers on the way back (post-order): sizes, DP on trees, finishing times. Pre-order is work before children; post-order is work after. That distinction is how topological sort and Kosaraju get finishing times.
Disconnected graphs need an outer loop over all nodes.
Code Examples
import java.util.List;
public class Components {
static void dfs(int u, boolean[] seen, List<List<Integer>> g) {
seen[u] = true;
for (int v : g.get(u)) {
if (!seen[v]) {
dfs(v, seen, g);
}
}
}
static int count(List<List<Integer>> g) {
boolean[] seen = new boolean[g.size()];
int n = 0;
for (int u = 0; u < g.size(); u++) {
if (!seen[u]) {
dfs(u, seen, g);
n++;
}
}
return n;
}
public static void main(String[] args) {
List<List<Integer>> g = List.of(List.of(1), List.of(0), List.of());
System.out.println(count(g)); // prints: 2
}
}import java.util.List;
public class Cycle {
static boolean dfs(int u, int[] color, List<List<Integer>> g) {
color[u] = 1; // on stack
for (int v : g.get(u)) {
if (color[v] == 1) {
return true;
}
if (color[v] == 0 && dfs(v, color, g)) {
return true;
}
}
color[u] = 2; // done
return false;
}
public static void main(String[] args) {
List<List<Integer>> g = List.of(List.of(1), List.of(2), List.of(0));
System.out.println(dfs(0, new int[3], g)); // prints: true
}
}Common Gotchas
Deep recursion throws `StackOverflowError`
use an explicit stack on tall graphs.
Directed cycle detection needs three colours
a finished neighbour is not a cycle.
First time you reach a node is not a shortest path
use BFS for hops.
Forgetting the outer loop misses disconnected components
Forgetting the outer loop misses disconnected components