has_cycle_directed

Function has_cycle_directed 

Source
pub fn has_cycle_directed<G>(graph: &G) -> bool
where G: Graph,
Expand description

Returns true if the directed graph contains at least one cycle.

Uses three-colour DFS: a back-edge (an edge to a Gray node that is still on the current DFS path) proves a cycle exists.

§Examples

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

// Acyclic: A → B → C
let mut dag: AdjacencyList<()> = AdjacencyList::directed();
let a = dag.add_node(());
let b = dag.add_node(());
let c = dag.add_node(());
dag.add_edge(a, b, 1.0).unwrap();
dag.add_edge(b, c, 1.0).unwrap();
assert!(!has_cycle_directed(&dag));

// Cyclic: A → B → A
let mut cyclic: AdjacencyList<()> = AdjacencyList::directed();
let a = cyclic.add_node(());
let b = cyclic.add_node(());
cyclic.add_edge(a, b, 1.0).unwrap();
cyclic.add_edge(b, a, 1.0).unwrap();
assert!(has_cycle_directed(&cyclic));