37/40
Part 8 of 8 · Follow-upsLearn and do
Dijkstra's algorithm pops the nearest node, and is correct only when no edge is negative
Breadth-first search explores a graph in rings: every node one step from the start, then every node two steps away, and so on, taken from a first-in, first-out queue. That finds the fewest steps when every step costs the same. When edges have different costs, say network delays, swap its queue for a heap of (distance so far, node). Then always settle the nearest unsettled node next.
A node can be pushed more than once, with different distances. So skip an entry for a node already settled. That's lazy deletion again.
links = [("a", "b", 4), ("a", "c", 1), ("c", "b", 2),
("b", "d", 5), ("c", "d", 8), ("d", "e", 3)]
print(delays(links, "a"))
Links a to b 4, a to c 1, c to b 2, b to d 5, c to d 8, d to e 3. What's the shortest delay from a to e?
Pick one to see what it prints.
Pick an answer above to see the rest