Skip to content

Instantly share code, notes, and snippets.

@matthewjberger
Last active May 22, 2024 06:11
Show Gist options
  • Save matthewjberger/2e94174c644c9ddadedfd7f7fb595980 to your computer and use it in GitHub Desktop.
Save matthewjberger/2e94174c644c9ddadedfd7f7fb595980 to your computer and use it in GitHub Desktop.
// petgraph v0.6.5
use petgraph::graph::DiGraph;
use petgraph::visit::{EdgeRef, Topo};
fn main() {
// Create a new directed graph
let mut graph = DiGraph::new();
// Add nodes and edges (similar to previous examples)
let a1 = graph.add_node("A1");
let b1 = graph.add_node("B1");
let b2 = graph.add_node("B2");
let c1 = graph.add_node("C1");
let c2 = graph.add_node("C2");
let c3 = graph.add_node("C3");
let c4 = graph.add_node("C4");
graph.add_edge(a1, b1, ());
graph.add_edge(a1, b2, ());
graph.add_edge(b1, c1, ());
graph.add_edge(b1, c2, ());
graph.add_edge(b2, c3, ());
graph.add_edge(b2, c4, ());
// Perform topological sort
let mut topo = Topo::new(&graph);
// Traverse the graph using topological order
while let Some(node) = topo.next(&graph) {
let mut stack = vec![node];
let mut chain = vec![];
// Traverse up the graph from the current node to the root
while let Some(curr_node) = stack.pop() {
chain.push(curr_node);
if let Some(parent) = graph
.edges_directed(curr_node, petgraph::Direction::Incoming)
.next()
.map(|edge| edge.source())
{
stack.push(parent);
}
}
chain.reverse();
println!(
"Parent chain of {:?}: {:?}",
graph[node],
chain
.iter()
.map(|idx| graph[*idx])
.collect::<Vec<_>>()
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment