8000 Minor improvement. · anubhavcoder/practice-python@bd3a7eb · GitHub
[go: up one dir, main page]

Skip to content

Commit bd3a7eb

Browse files
committed
Minor improvement.
1 parent 6fa1f06 commit bd3a7eb

File tree

1 file changed

+7
-0
lines changed

1 file changed

+7
-0
lines changed

graphs/dijkstra.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,13 +39,17 @@ def dijkstra(graph, source, dest):
3939

4040
while not q.empty():
4141
v_tuple = q.get()
42+
# skip obsolete items that were superceded by new inserts
43+
if v_tuple[0] == float("inf"):
44+
continue
4245
v = v_tuple[1]
4346

4447
for e in graph.get_edge(v):
4548
candidate_distance = distances[v] + e.weight
4649
if distances[e.vertex] > candidate_distance:
4750
distances[e.vertex] = candidate_distance
4851
parents[e.vertex] = v
52+
# reinsert into queue with new key because decrease-key not supported
4953
q.put(([distances[e.vertex], e.vertex]))
5054

5155
shortest_path = []
@@ -86,6 +90,9 @@ def main():
8690
g.add_edge(8, 7, 2)
8791
g.add_edge(8, 6, 2)
8892

93+
shortest_path, distance = dijkstra(g, 0, 1)
94+
assert shortest_path == [0, 1] and distance == 4
95+
8996
shortest_path, distance = dijkstra(g, 0, 8)
9097
assert shortest_path == [0, 1, 2, 3, 7, 8] and distance == 11
9198

0 commit comments

Comments
 (0)
0