1.求最小距离 Dijkstra algorithm
其实就是一个BFS问题,只是BFS运行的时候每次是入queue,Dijkstra每次是入heap(每次出最小的)。
1. 初始化 disTo 为所有都为 正无穷, 除了起始点为0。
2. 初始化 heapq 为所有以出发点为起点的边。
3. 如果disTo[v] > disTo[u] + dis(当找到一个更小的距离), 更新距离,并且把其所有边加入heap
4. 直到heap为空
class Solution:
def networkDelayTime(self, times: List[List[int]], N: int, K: int) -> int:
graph = {}
disTo = {}
pq = []
# 1. build the graph
# 2. make distance to every point infinity
for time in times:
start = time[0]
end = time[1]
dis = time[2]
disTo[start] = float("inf")
disTo[end] = float("inf")
if start not in graph:
graph[start] = [[dis, end]]
else:
graph[start].append([dis, end])
if start == K:
heapq.heappush(pq, [dis, start, end])
# init the pq with start point with dis = 0
disTo[K] = 0
while pq:
this = heapq.heappop(pq)
u = this[1]
v = this[2]
dis = this[0]
#加入新的路径小于之前的路径,则更新,并且将子节点