Skip to content

Instantly share code, notes, and snippets.

@sausheong
Created May 3, 2022 02:59
Show Gist options
  • Save sausheong/645888e8c533aaa306b883332264fd32 to your computer and use it in GitHub Desktop.
Save sausheong/645888e8c533aaa306b883332264fd32 to your computer and use it in GitHub Desktop.
mst
// Kruskal's algorithm for Minimum Spanning Tree
func kruskal(graph *Graph) (mst *Graph) {
mst = NewGraph()
h := &Heap{}
heap.Init(h)
// get a sorted list of edges
for nodeName, edges := range graph.Edges {
node := graph.GetNode(nodeName)
for _, edge := range edges {
heap.Push(h, NodePair{node, edge})
}
mst.AddNode(node)
}
for len(*h) > 0 {
pair := heap.Pop(h).(NodePair)
// if the edge isn't there between pair of nodes in the MST, create it
if !mst.HasEdge(pair.node.name, pair.edge) {
mst.AddEdge(pair.node, pair.edge.node, pair.edge.weight)
// but if it creates a cyclical graph, remove it
if mst.isCyclic(pair.node.name) {
mst.RemoveEdge(pair.node.name, pair.edge.node.name)
}
}
}
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment