DFS
Depth-first search walks a graph by going as deep as possible before backtracking. Implement it with the call stack or with an explicit Vec stack.
Detailed Explanation
DFS picks a neighbour, then a neighbour of that neighbour, and only when a path is exhausted does it try the next unused edge. That is the opposite of BFS's level order. The data structure is a stack. Recursion is a stack. Vec plus push/pop is a stack.
Use DFS for reachability, cycle detection (keep a recursion-stack colour: white / grey / black), topological sort on a DAG (finish times), connected components in an undirected graph, and some path-enumeration problems. Do not use it for unweighted shortest path; BFS is the one that finds fewest edges.
The recursive form is short and overflows on a long path. In Rust that overflow is a crash, not a Result. For user-controlled graphs, write the explicit stack. Store the iterator of remaining neighbours in the stack frame if you need to resume a node after backtracking; a naive "push all neighbours" stack is still DFS but a different child order.
Colouring for cycles: a node on the current path is grey. Seeing a grey neighbour is a back edge and a cycle in a directed graph. In an undirected graph you must ignore the parent edge. A seen set alone cannot distinguish a back edge from a cross edge.
Borrowing: a recursive &mut self walk of a tree can work if children are distinct fields or you split them. A recursive walk of a Vec<Vec<usize>> graph should pass the graph as &[Vec<usize>] and keep seen as &mut [bool]. That splits the borrows cleanly.
When you reach for DFS: structure, cycles, topo sort, tree properties. When you reach for BFS: distance in edges. When you reach for an explicit stack: depth that you do not trust.
Code Examples
fn dfs(adj: &[Vec<usize>], start: usize) -> Vec<bool> {
let mut seen = vec![false; adj.len()];
let mut stack = vec![start];
while let Some(u) = stack.pop() {
if seen[u] {
continue;
}
seen[u] = true;
for &v in &adj[u] {
if !seen[v] {
stack.push(v);
}
}
}
seen
}
fn main() {
let adj = vec![vec![1], vec![2], vec![]];
println!("{:?}", dfs(&adj, 0)); // prints: [true, true, true]
}Common Gotchas
Recursive DFS on a long path overflows the stack
Use a `Vec` stack for untrusted or huge graphs.
Cycle detection needs three colours on directed graphs
A boolean `seen` is not enough to know whether the neighbour is on the current path.
`pop` is DFS, `pop_front` is BFS
The rest of the code can look identical. Check the queue type.
Parent edges look like cycles in undirected graphs
Pass the parent and skip it, or use a directed model.