Now compute the shortest distance from a source to every reachable node. This is exactly what a router does to learn the lowest-latency cost to reach each destination.
Implement shortest_distances(source) using Dijkstra's algorithm:
Return the dist dict. Unreachable nodes are simply omitted from the dict (callers treat a missing node as infinity). All weights are non-negative.
import heapq
class WeightedGraph:
def __init__(self):
self.adj = {}
def add_edge(self, u, v, w):
if u not in self.adj:
self.adj[u] = []
self.adj[u].append((v, w))
def neighbors(self, u):
return self.adj.get(u, [])
def shortest_distances(self, source):
"""Return dict of node -> shortest distance from source (Dijkstra)."""
# TODO: run Dijkstra with a heap and return the distance dict
pass
The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
Now compute the shortest distance from a source to every reachable node. This is exactly what a router does to learn the lowest-latency cost to reach each destination.
Implement shortest_distances(source) using Dijkstra's algorithm:
Return the dist dict. Unreachable nodes are simply omitted from the dict (callers treat a missing node as infinity). All weights are non-negative.
Press Run Tests or ββ© to check your solution.