Last active
May 3, 2022 04:54
-
-
Save sausheong/12274dcf8f0dce1d4e44afdafc53d220 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
func prim(graph *Graph, nodeName string) (mst *Graph) { | |
mst = NewGraph() | |
h := &Heap{} | |
heap.Init(h) | |
startNode := graph.GetNode(nodeName) | |
mst.AddNode(startNode) | |
for _, edge := range graph.Edges[startNode.name] { | |
heap.Push(h, NodePair{startNode, edge}) | |
} | |
for len(*h) > 0 { | |
// get the edge with the smallest weight | |
pair := heap.Pop(h).(NodePair) | |
// skip if the node pair is already in the MST | |
if !mst.HasNode(pair.edge.node.name) { | |
// add the node and the edge to the MST | |
mst.AddNode(pair.edge.node) | |
mst.AddEdge(pair.node, pair.edge.node, pair.edge.weight) | |
// add all the edges going from the connected node into the heap | |
for _, edge := range graph.Edges[pair.edge.node.name] { | |
heap.Push(h, NodePair{pair.edge.node, edge}) | |
} | |
} | |
} | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment