-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
kruskal.go
51 lines (42 loc) · 1.52 KB
/
kruskal.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// KRUSKAL'S ALGORITHM
// Reference: Kruskal's Algorithm: https://www.scaler.com/topics/data-structures/kruskal-algorithm/
// Reference: Union Find Algorithm: https://www.scaler.com/topics/data-structures/disjoint-set/
// Author: Author: Mugdha Behere[https://github.com/MugdhaBehere]
// Worst Case Time Complexity: O(E log E), where E is the number of edges.
// Worst Case Space Complexity: O(V + E), where V is the number of vertices and E is the number of edges.
// see kruskal.go, kruskal_test.go
package graph
import (
"sort"
)
type Vertex int
type Edge struct {
Start Vertex
End Vertex
Weight int
}
func KruskalMST(n int, edges []Edge) ([]Edge, int) {
// Initialize variables to store the minimum spanning tree and its total cost
var mst []Edge
var cost int
// Create a new UnionFind data structure with 'n' nodes
u := NewUnionFind(n)
// Sort the edges in non-decreasing order based on their weights
sort.SliceStable(edges, func(i, j int) bool {
return edges[i].Weight < edges[j].Weight
})
// Iterate through the sorted edges
for _, edge := range edges {
// Check if adding the current edge forms a cycle or not
if u.Find(int(edge.Start)) != u.Find(int(edge.End)) {
// Add the edge to the minimum spanning tree
mst = append(mst, edge)
// Add the weight of the edge to the total cost
cost += edge.Weight
// Merge the sets containing the start and end vertices of the current edge
u.Union(int(edge.Start), int(edge.End))
}
}
// Return the minimum spanning tree and its total cost
return mst, cost
}