Created
May 3, 2022 02:59
-
-
Save sausheong/645888e8c533aaa306b883332264fd32 to your computer and use it in GitHub Desktop.
mst
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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