Debian Codegraph @

mst.go

raw symbols SCIP
1 package graph
2
3 // MST computes a minimum spanning tree for each connected component
4 // of an undirected weighted graph.
5 // The forest of spanning trees is returned as a slice of parent pointers:
6 // parent[v] is either the parent of v in a tree,
7 // or -1 if v is the root of a tree.
8 //
9 // The time complexity is O(|E|⋅log|V|), where |E| is the number of edges
10 // and |V| the number of vertices in the graph.
11 func MST(g Iterator) (parent []int) {
12 n := g.Order()
13 parent = make([]int, n)
14 cost := make([]int64, n)
15 for i := range parent {
16 parent[i] = -1
17 cost[i] = Max
18 }
19
20 // Prim's algorithm
21 Q := newPrioQueue(cost)
22 for Q.Len() > 0 {
23 v := Q.Pop()
24 g.Visit(v, func(w int, c int64) (skip bool) {
25 if Q.Contains(w) && c < cost[w] {
26 cost[w] = c
27 Q.Fix(w)
28 parent[w] = v
29 }
30 return
31 })
32 }
33 return
34 }