Skip to content

Commit 36bfd4e

Browse files
authored
Add Minimum Spanning Tree in Go (#5770)
1 parent dab9b07 commit 36bfd4e

1 file changed

Lines changed: 107 additions & 0 deletions

File tree

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"math"
6+
"os"
7+
"strconv"
8+
"strings"
9+
)
10+
11+
const usage = `Usage: please provide a comma-separated list of integers`
12+
13+
func main() {
14+
if len(os.Args) != 2 {
15+
printUsage()
16+
}
17+
18+
matrix, errM := parseList(os.Args[1])
19+
20+
if errM != nil {
21+
printUsage()
22+
}
23+
24+
nFloat := math.Sqrt(float64(len(matrix)))
25+
n := int(nFloat)
26+
if nFloat != float64(n) || n == 0 {
27+
printUsage()
28+
}
29+
30+
cost, ok := primMST(matrix, n)
31+
if !ok {
32+
printUsage()
33+
}
34+
35+
fmt.Println(cost)
36+
}
37+
38+
func primMST(matrix []int, n int) (int, bool) {
39+
if n == 0 {
40+
return 0, true
41+
}
42+
43+
inMST := make([]bool, n)
44+
minWeights := make([]int, n)
45+
for i := range minWeights {
46+
minWeights[i] = math.MaxInt32
47+
}
48+
49+
minWeights[0] = 0
50+
totalWeight := 0
51+
nodesInTree := 0
52+
53+
for i := 0; i < n; i++ {
54+
u := -1
55+
minVal := math.MaxInt32
56+
57+
for v := 0; v < n; v++ {
58+
if !inMST[v] && minWeights[v] < minVal {
59+
minVal = minWeights[v]
60+
u = v
61+
}
62+
}
63+
64+
if u == -1 {
65+
break
66+
}
67+
68+
inMST[u] = true
69+
totalWeight += minVal
70+
nodesInTree++
71+
72+
for v := 0; v < n; v++ {
73+
weight := matrix[u*n+v]
74+
if weight > 0 && !inMST[v] && weight < minWeights[v] {
75+
minWeights[v] = weight
76+
}
77+
}
78+
}
79+
80+
if nodesInTree != n {
81+
return 0, false
82+
}
83+
84+
return totalWeight, true
85+
}
86+
87+
func parseList(input string) ([]int, error) {
88+
if strings.TrimSpace(input) == "" {
89+
return nil, fmt.Errorf("empty input")
90+
}
91+
92+
parts := strings.Split(input, ",")
93+
nums := make([]int, 0, len(parts))
94+
for _, p := range parts {
95+
val, err := strconv.Atoi(strings.TrimSpace(p))
96+
if err != nil {
97+
return nil, err
98+
}
99+
nums = append(nums, val)
100+
}
101+
return nums, nil
102+
}
103+
104+
func printUsage() {
105+
fmt.Println(usage)
106+
os.Exit(1)
107+
}

0 commit comments

Comments
 (0)