topological_sort_kahn

Function topological_sort_kahn 

Source
pub fn topological_sort_kahn<G>(graph: &G) -> Result<Vec<NodeId>, GraphError>
where G: Graph,
Expand description

Returns a topological ordering using Kahn’s algorithm (in-degree BFS).

Processes nodes with in-degree 0 first; decrementing neighbours’ in-degrees as each node is emitted. If not all nodes are emitted the graph has a cycle.

§Errors

Returns Err(GraphError::InvalidOperation) if a cycle is detected.

§Examples

use graph_core::{AdjacencyList, Graph};
use graph_traversal::topological_sort_kahn;

let mut g: AdjacencyList<()> = AdjacencyList::directed();
let a = g.add_node(());
let b = g.add_node(());
let c = g.add_node(());
g.add_edge(a, b, 1.0).unwrap();
g.add_edge(a, c, 1.0).unwrap();
g.add_edge(b, c, 1.0).unwrap();

let order = topological_sort_kahn(&g).unwrap();
let pos: std::collections::HashMap<_, _> =
    order.iter().enumerate().map(|(i, &n)| (n, i)).collect();
assert!(pos[&a] < pos[&b]);
assert!(pos[&b] < pos[&c]);