-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.go
58 lines (53 loc) · 1.03 KB
/
Solution.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
52
53
54
55
56
57
58
const inf = 1 << 29
type Graph struct {
g [][]int
}
func Constructor(n int, edges [][]int) Graph {
g := make([][]int, n)
for i := range g {
g[i] = make([]int, n)
for j := range g[i] {
g[i][j] = inf
}
}
for _, e := range edges {
f, t, c := e[0], e[1], e[2]
g[f][t] = c
}
return Graph{g}
}
func (this *Graph) AddEdge(edge []int) {
f, t, c := edge[0], edge[1], edge[2]
this.g[f][t] = c
}
func (this *Graph) ShortestPath(node1 int, node2 int) int {
n := len(this.g)
dist := make([]int, n)
for i := range dist {
dist[i] = inf
}
vis := make([]bool, n)
dist[node1] = 0
for i := 0; i < n; i++ {
t := -1
for j := 0; j < n; j++ {
if !vis[j] && (t == -1 || dist[t] > dist[j]) {
t = j
}
}
vis[t] = true
for j := 0; j < n; j++ {
dist[j] = min(dist[j], dist[t]+this.g[t][j])
}
}
if dist[node2] >= inf {
return -1
}
return dist[node2]
}
/**
* Your Graph object will be instantiated and called as such:
* obj := Constructor(n, edges);
* obj.AddEdge(edge);
* param_2 := obj.ShortestPath(node1,node2);
*/