Skip to main content

random_spanning_tree

Function random_spanning_tree 

Source
pub fn random_spanning_tree(
    graph: &Graph,
    start_vertex: Option<u32>,
    seed: u64,
) -> IgraphResult<Vec<u32>>
Expand description

Uniformly sample a random spanning tree (or forest) of a graph.

Uses loop-erased random walk (Wilson’s algorithm). Edge directions are ignored. Multi-edges are supported and affect sampling frequency.

If start_vertex is Some(v), only the component containing v is spanned; the result has component_size - 1 edges. If start_vertex is None, a random spanning forest of all components is returned.

Returns a vector of edge IDs forming the spanning tree/forest.

§Errors

  • InvalidArgument if start_vertex is out of range.

§Examples

use rust_igraph::{Graph, random_spanning_tree};

// Triangle: any spanning tree has exactly 2 edges.
let mut g = Graph::with_vertices(3);
g.add_edge(0, 1).unwrap();
g.add_edge(1, 2).unwrap();
g.add_edge(0, 2).unwrap();
let tree = random_spanning_tree(&g, Some(0), 42).unwrap();
assert_eq!(tree.len(), 2);