Skip to main content

ac_lib/graph/
dfs.rs

1pub fn dfs(graph: &[Vec<usize>], start: usize, visited: &mut [bool]) -> Vec<usize> {
2    let mut order = Vec::new();
3    dfs_helper(graph, start, visited, &mut order);
4    order
5}
6
7fn dfs_helper(graph: &[Vec<usize>], node: usize, visited: &mut [bool], order: &mut Vec<usize>) {
8    visited[node] = true;
9    order.push(node);
10
11    for &neighbor in &graph[node] {
12        if !visited[neighbor] {
13            dfs_helper(graph, neighbor, visited, order);
14        }
15    }
16}
17
18pub fn dfs_with_callback<F>(
19    graph: &[Vec<usize>],
20    start: usize,
21    visited: &mut [bool],
22    callback: &mut F,
23) where
24    F: FnMut(usize),
25{
26    visited[start] = true;
27    callback(start);
28
29    for &neighbor in &graph[start] {
30        if !visited[neighbor] {
31            dfs_with_callback(graph, neighbor, visited, callback);
32        }
33    }
34}