cconnected.
Understand the pattern. Find your own way.Find your starting point
Your learning feed/Idea 73 of 218
Ideas this builds on
Graphs73 / 218

The cheapest frontier state can become final

Picture

BFS finalizes shortest edge counts by processing distance layers. With nonnegative varying edge costs, Dijkstra instead selects the smallest tentative total cost. The heap implements that selection; nonnegative costs justify it. The data structure alone is not the proof.

Predict

A vertex is first discovered with cost 10, then another route improves it to 3. Should first discovery permanently mark its distance final, as it can in ordinary BFS?

Reveal the reasoning

No. Discovery is tentative. In Dijkstra, extracting the current minimum valid entry is the safe commitment under nonnegative edge weights. An old heap entry for cost 10 can be ignored after the improvement.

Go deeper: why nonnegative edges matter

If the cheapest unsettled vertex has tentative distance d, a route through another unsettled vertex cannot later become cheaper by adding only nonnegative edges. More formally, a supposedly cheaper route has a first unsettled vertex whose settled predecessor would already have offered a tentative cost no larger than that route. That contradicts selecting a larger minimum.

Use integer vertex labels and adjacency lists of (neighbor, weight), assuming all weights are nonnegative.

from heapq import heappop, heappush

def cheapest_distances(graph, start):
    distances = {start: 0}
    heap = [(0, start)]
    while heap:
        cost, node = heappop(heap)
        if cost != distances[node]:
            continue
        for neighbor, weight in graph.get(node, []):
            candidate = cost + weight
            if candidate < distances.get(neighbor, float("inf")):
                distances[neighbor] = candidate
                heappush(heap, (candidate, neighbor))
    return distances

graph = {0: [(1, 10), (2, 1)], 2: [(1, 2)], 1: []}
assert cheapest_distances(graph, 0) == {0: 0, 1: 3, 2: 1}
assert cheapest_distances({}, 0) == {0: 0}

Relaxation means offering a better route through the current node. This implementation leaves outdated offers in the heap and skips them when popped. Its general bound is O((V+E) log(V+E)) time and O(V+E) extra space; for simple graphs the customary time bound is O((V+E) log V).

Analogy limit: this method assumes nonnegative edges. Adding a visited set or a heap does not make negative-edge shortest paths safe under the same proof. DAG shortest-path evaluation or Bellman–Ford may fit different conditions.

Change one rule

Every edge has cost exactly 1. Do you still need a heap?

Check the variation

No. BFS’s queue already processes the correct distance order in O(V+E) time. More general machinery is unnecessary for that uniform-cost contract.

Connect

DAG dependencies offer another shortest-path evaluation order when acyclicity holds. Connectivity asks a simpler question than distances. Recognition chooses based on guarantees and the requested output.