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
| const INFINITY = math.MaxInt64
func networkDelayTime(times [][]int, n int, k int) int { D := make(map[int]int) S := make(map[int]bool)
for i := 1; i <= n; i++ { D[i] = INFINITY } D[k] = 0 DISTANCE := make(map[string]int) for _, edge := range times { DISTANCE[strconv.Itoa(edge[0])+" "+strconv.Itoa(edge[1])] = edge[2] }
for { u := extractMin(D, S) if u == -1 { break } S[u] = true for v, dist := range D { if _, ok := S[v]; !ok { uv := edge(u, v, DISTANCE) if uv != -1 { if D[u]+uv < dist { D[v] = D[u] + uv } } } } }
max := -1 for _, distance := range D { if distance == INFINITY { return -1 } if distance > max && distance != 0 { max = distance } } return max }
func edge(u, v int, distance map[string]int) int { d, ok := distance[strconv.Itoa(u)+" "+strconv.Itoa(v)] if !ok { return -1 } return d }
func extractMin(D map[int]int, S map[int]bool) int { minDistance := INFINITY ans := -1 for node, distance := range D { if _, ok := S[node]; !ok { if distance < minDistance { ans = node minDistance = distance } } } return ans }
|