Expand description
Uniform random labelled tree generators (ALGO-GN-004).
Counterpart of igraph_tree_game() in
references/igraph/src/games/tree.c. Two methods are available:
- LERW (
tree_game_lerw) — Wilson’s loop-erased random walk onK_n. Supports both directed (out-rooted) and undirected trees. - Prüfer (
tree_game_prufer) — samples a random Prüfer sequence, then decodes it viafrom_prufer. Undirected only, matching the C upstream restriction.
Both methods produce each labelled tree with equal probability.
§LERW algorithm
Wilson’s loop-erased random walk on the complete graph K_n uniformly
samples spanning trees. The igraph implementation collapses the naive
“walk until you hit a visited vertex, then erase the loop” formulation
into a single linear pass:
- Maintain an array
vertices = [0, 1, …, n - 1]partitioned so that positions[0, k)hold the visited vertices and[k, n)hold the unvisited ones. - Pick an initial vertex
iuniformly, mark it visited, swap it to position0, setk = 1. - For each remaining step
k = 1 .. n: drawj ∈ [0, n). Ifvertices[j]is already visited (its slot lies in[0, k)), advance the walk by settingi = vertices[j]and resamplej ∈ [k, n)so the next visited vertex is guaranteed to be a fresh one. Then markvertices[j]visited, swap it to positionk, emit the edge(i, vertices[k]), and updatei = vertices[k].
Each iteration produces exactly one edge, so the tree has n - 1
edges. Runtime is O(n) walk steps amortised — there is no rejection
loop because step 3a covers the “already visited” branch in one shot.
§Prüfer algorithm
Generate n - 2 uniform random values in [0, n), forming a Prüfer
sequence, then decode it with the linear-time algorithm from
from_prufer. The result is always an undirected
labelled tree.
Functions§
- tree_
game_ lerw - Generate a uniformly random labelled tree on
nvertices using Wilson’s loop-erased random walk. - tree_
game_ prufer - Generate a uniformly random labelled tree on
nvertices using the Prüfer sequence method.