euler_circuit

Function euler_circuit 

Source
pub fn euler_circuit<G>(graph: &G) -> Result<Vec<NodeId>, EulerError>
where G: Graph<Weight = f64>,
Expand description

Finds an Euler circuit in an undirected graph using Hierholzer’s algorithm.

An Euler circuit visits every edge exactly once and returns to the starting node. It exists iff the graph is connected (ignoring isolated nodes) and every node has even degree.

§Returns

Ok(Vec<NodeId>) — the sequence of nodes visited, with the first node repeated at the end (first == last).

§Errors

§Complexity

O(E) — Hierholzer’s algorithm visits each edge exactly twice (once per direction in the undirected adjacency list).

§Examples

use graph_core::{AdjacencyList, Graph};
use graph_advanced::euler_circuit;

// Complete graph K3: triangle — Euler circuit exists.
let mut g: AdjacencyList<()> = AdjacencyList::undirected();
let n: Vec<_> = (0..3).map(|_| g.add_node(())).collect();
g.add_edge(n[0], n[1], 1.0).unwrap();
g.add_edge(n[1], n[2], 1.0).unwrap();
g.add_edge(n[2], n[0], 1.0).unwrap();

let circuit = euler_circuit(&g).unwrap();
assert_eq!(circuit.len(), 4); // 3 edges + return to start
assert_eq!(circuit.first(), circuit.last());