-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdag_algorithm.go
More file actions
109 lines (97 loc) · 1.64 KB
/
Copy pathdag_algorithm.go
File metadata and controls
109 lines (97 loc) · 1.64 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package main
import (
"fmt"
)
type Graph map[string]map[string]uint
var (
processed []string
)
func main() {
graph := makeGraph()
costs := makeCosts()
parents := makeParents()
node := findLowestCostNode(costs, processed)
for node != "" {
cost := costs[node]
neighbors := graph[node]
for n := range neighbors {
newCost := cost + neighbors[n]
if costs[n] > newCost {
costs[n] = newCost
parents[n] = node
}
}
processed = append(processed, node)
node = findLowestCostNode(costs, processed)
}
fmt.Printf("the shortest path is %d\n", costs["fin"])
fmt.Println("the path is:", parents)
}
func makeGraph() Graph {
tree := Graph{
"start": {
"a": 5,
"b": 2,
},
"a": {
"c": 4,
"d": 2,
},
"b": {
"a": 8,
"d": 7,
},
"c": {
"d": 6,
"fin": 3,
},
"d": {
"fin": 1,
},
"fin": {},
}
return tree
}
func makeCosts() map[string]uint {
costs := map[string]uint{
"a": 5,
"b": 2,
"c": ^uint(0),
"d": ^uint(0),
"fin": ^uint(0),
}
return costs
}
func makeParents() map[string]string {
parents := map[string]string{
"a": "start",
"b": "start",
"fin": "",
}
return parents
}
func findLowestCostNode(costs map[string]uint, processed []string) string {
var (
lowestCostNode string
)
lowestCost := ^uint(0)
for k := range costs {
cost := costs[k]
if cost < lowestCost && !sliceContainsString(processed, k) {
lowestCost = cost
lowestCostNode = k
}
}
return lowestCostNode
}
func sliceContainsString(slice []string, val string) bool {
if slice == nil {
return false
}
for _, k := range slice {
if k == val {
return true
}
}
return false
}