@@ -38,7 +38,8 @@ def __eq__(self, other: DijkstraNode) -> bool:
3838
3939def dijkstra (wg : WeightedGraph [V ], root : V ) -> Tuple [List [Optional [float ]], Dict [int , WeightedEdge ]]:
4040 first : int = wg .index_of (root ) # find starting index
41- distances : List [Optional [float ]] = [None ] * wg .vertex_count # distances are unknown at first
41+ # distances are unknown at first
42+ distances : List [Optional [float ]] = [None ] * wg .vertex_count
4243 distances [first ] = 0 # the root is 0 away from the root
4344 path_dict : Dict [int , WeightedEdge ] = {} # how we got to each vertex
4445 pq : PriorityQueue [DijkstraNode ] = PriorityQueue ()
@@ -47,12 +48,18 @@ def dijkstra(wg: WeightedGraph[V], root: V) -> Tuple[List[Optional[float]], Dict
4748 while not pq .empty :
4849 u : int = pq .pop ().vertex # explore the next closest vertex
4950 dist_u : float = distances [u ] # should already have seen it
50- for we in wg .edges_for_index (u ): # look at every edge/vertex from the vertex in question
51- dist_v : float = distances [we .v ] # the old distance to this vertex
52- if dist_v is None or dist_v > we .weight + dist_u : # no old distance or found shorter path
53- distances [we .v ] = we .weight + dist_u # update distance to this vertex
54- path_dict [we .v ] = we # update the edge on the shortest path to this vertex
55- pq .push (DijkstraNode (we .v , we .weight + dist_u )) # explore it soon
51+ # look at every edge/vertex from the vertex in question
52+ for we in wg .edges_for_index (u ):
53+ # the old distance to this vertex
54+ dist_v : float = distances [we .v ]
55+ # no old distance or found shorter path
56+ if dist_v is None or dist_v > we .weight + dist_u :
57+ # update distance to this vertex
58+ distances [we .v ] = we .weight + dist_u
59+ # update the edge on the shortest path to this vertex
60+ path_dict [we .v ] = we
61+ # explore it soon
62+ pq .push (DijkstraNode (we .v , we .weight + dist_u ))
5663
5764 return distances , path_dict
5865
0 commit comments