has_cycle_undirected

Function has_cycle_undirected 

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

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

Uses DFS with parent tracking. A back-edge to any node other than the immediate DFS parent signals a cycle.

§Examples

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

// Tree (no cycle): A — B — C
let mut tree: AdjacencyList<()> = AdjacencyList::undirected();
let a = tree.add_node(());
let b = tree.add_node(());
let c = tree.add_node(());
tree.add_edge(a, b, 1.0).unwrap();
tree.add_edge(b, c, 1.0).unwrap();
assert!(!has_cycle_undirected(&tree));

// Triangle: A — B — C — A
let mut tri: AdjacencyList<()> = AdjacencyList::undirected();
let a = tri.add_node(());
let b = tri.add_node(());
let c = tri.add_node(());
tri.add_edge(a, b, 1.0).unwrap();
tri.add_edge(b, c, 1.0).unwrap();
tri.add_edge(c, a, 1.0).unwrap();
assert!(has_cycle_undirected(&tri));