Shortest distances with weights

graph is a dictionary from each node to a list of (neighbour, weight) pairs with non-negative weights; every node is a key. Write distances(graph, source) that returns a dictionary from every reachable node to its shortest total distance from source.

graph = {"A": [("B", 4), ("C", 1)], "B": [("D", 1)], "C": [("B", 2), ("D", 5)], "D": []}
distances(graph, "A")  ->  {"A": 0, "B": 3, "C": 1, "D": 4}

This is Dijkstra's algorithm: breadth-first search with the queue replaced by a heap of (distance, node), so the closest unsettled node is always processed next.

def distances(graph, source):
    ...