Skip to main content

find_cycle

Function find_cycle 

Source
pub fn find_cycle(graph: &Graph, mode: CycleMode) -> IgraphResult<CycleResult>
Expand description

Finds a single cycle in the graph, if one exists.

Uses iterative DFS to find a back-edge, then extracts the cycle from the DFS path. Returns empty vectors if the graph is acyclic.

For undirected graphs, mode is ignored and treated as All.

§Examples

use rust_igraph::{Graph, find_cycle, CycleMode};

// Directed cycle: 0→1→2→0
let mut g = Graph::new(3, true).unwrap();
g.add_edge(0, 1).unwrap();
g.add_edge(1, 2).unwrap();
g.add_edge(2, 0).unwrap();

let result = find_cycle(&g, CycleMode::Out).unwrap();
// Cycle 0→1→2→0: vertices=[0,1,2,0], edges=[e0,e1,e2]
assert_eq!(result.vertices.len(), 4);
assert_eq!(result.edges.len(), 3);
assert_eq!(result.vertices.first(), result.vertices.last());

// DAG: no cycle
let mut g = Graph::new(3, true).unwrap();
g.add_edge(0, 1).unwrap();
g.add_edge(0, 2).unwrap();

let result = find_cycle(&g, CycleMode::Out).unwrap();
assert!(result.vertices.is_empty());