Last active
January 7, 2024 04:01
-
-
Save matthewjberger/5c3c2e29c2b77846b8e279fe81f741a5 to your computer and use it in GitHub Desktop.
Recursively walk a petgraph directed graph
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn visit_graph_recursively<N, E, VM>( | |
graph: &petgraph::graph::DiGraph<N, E>, | |
visit_map: &mut VM, | |
node_idx: petgraph::graph::NodeIndex, | |
) where | |
N: std::fmt::Debug, | |
VM: petgraph::visit::VisitMap<petgraph::graph::NodeIndex>, | |
{ | |
// Mark the current node as visited | |
visit_map.visit(node_idx); | |
// Print details of the node, here it's just the index | |
println!("Visited node: {:?}", node_idx); | |
// Recursively visit unvisited neighbors | |
for neighbor in graph.neighbors(node_idx) { | |
if !visit_map.is_visited(&neighbor) { | |
visit_graph_recursively(graph, visit_map, neighbor); | |
} | |
} | |
} | |
fn main() { | |
// Create a directed graph | |
let mut graph = petgraph::graph::DiGraph::<&str, ()>::new(); | |
// Add nodes and edges here as needed | |
let a = graph.add_node("A"); | |
let b = graph.add_node("B"); | |
graph.add_edge(a, b, ()); | |
// Create a visitor map | |
use petgraph::visit::Visitable; | |
let mut visit_map = graph.visit_map(); | |
// Start the recursive visit from node 'a' | |
visit_graph_recursively(&graph, &mut visit_map, a); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment