执行用时:412 ms, 在所有 Swift 提交中击败了100.00%的用户
内存消耗:13.9 MB, 在所有 Swift 提交中击败了100.00%的用户
解题思路
每次找最短路径,到其他各点的最短路径中的最大值也就是消息能发到的最少时间
如果还有一个正无穷也就是到不了的距离,说明无法全部送到
代码
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
| class Solution { func networkDelayTime(_ times: [[Int]], _ n: Int, _ k: Int) -> Int { let maxDist = Int.max/2 var graph = [[Int]](repeating: [Int](repeating: maxDist, count: n), count: n) for i in 0 ..< times.count { let x = times[i][0] - 1, y = times[i][1] - 1 graph[x][y] = times[i][2] } var dist = [Int](repeating: maxDist, count: n) dist[k - 1] = 0; var used = [Bool](repeating: false, count: n) for _ in 0 ..< n { var x = -1 for y in 0 ..< n { if (!used[y] && (x == -1 || dist[y] < dist[x])) { x = y } } used[x] = true for y in 0 ..< n { dist[y] = min(dist[y], dist[x] + graph[x][y]) } } let res = dist.max()! return res == maxDist ? -1 : res } }
|