Privacy note: We capture your IP address to provide customised and focused services. See our Privacy Policy.

Algorithms & Competitive Programming — Alpha School

Lesson 16: Shortest Paths — Dijkstra, Bellman-Ford and Graph Problems

Breadth-first search finds the shortest path when every edge costs the same. But real roads have lengths, flights have prices, and network links have delays — edges have weights, and the shortest path is the one with the smallest total weight, not the fewest edges. Dijkstra's algorithm solves this for graphs with non-negative weights. It keeps a running best distance to every node, always expands the unvisited node with the smallest distance, and relaxes its edges — if going through this node gives a neighbour a shorter route, update it. A priority queue (a heap) makes finding the next node fast, giving O((V + E) log V) time.

The key idea is that once Dijkstra's algorithm picks a node as the closest unvisited one, its distance is final — no later route can beat it, because every edge weight is non-negative, so any detour only adds distance. That is also why Dijkstra's algorithm fails with negative weights: a negative edge could offer a shortcut discovered later, breaking the guarantee. For graphs with negative edges (but no negative cycles), the Bellman-Ford algorithm is the answer: it relaxes every edge, over and over, V - 1 times — enough for the shortest path to propagate — and then checks once more to detect a negative cycle.

import heapq


def dijkstra(graph, start):
    # graph: {node: [(neighbour, weight), ...]} with non-negative weights
    dist = {start: 0}
    pq = [(0, start)]
    while pq:
        d, node = heapq.heappop(pq)
        if d != dist.get(node):
            continue  # an outdated entry for this node
        for nb, w in graph[node]:
            nd = d + w
            if nd < dist.get(nb, float("inf")):
                dist[nb] = nd
                heapq.heappush(pq, (nd, nb))
    return dist


roads = {"A": [("B", 4), ("C", 2)], "B": [("D", 5)],
         "C": [("B", 1), ("D", 8)], "D": []}
print(dijkstra(roads, "A"))  # {'A': 0, 'B': 3, 'C': 2, 'D': 8}

Which shortest-path algorithm, when?

The choice is a small decision tree. If all edges weigh the same, use BFS — it is simpler and faster. If weights are non-negative, use Dijkstra's algorithm. If weights can be negative but there is no negative cycle, use Bellman-Ford. If there is a negative cycle — a loop whose total weight is negative, so going round it forever keeps reducing the distance — then no shortest path exists at all, and Bellman-Ford's extra pass detects it. These three cover nearly every shortest-path problem you will meet, and recognising which one fits is a matter of asking two questions: are the weights equal, and can they be negative?

Shortest paths are also a reminder that graph problems reward modelling. A problem about currency exchange, with rates as edge weights, becomes a shortest-path problem after taking logarithms. A problem about the fewest moves in a puzzle becomes a BFS over states. A problem about connecting cities cheaply becomes a minimum spanning tree. The skill is not memorising algorithms — it is seeing the graph inside the problem, and then picking the right tool for the graph you found.

Going further

Dijkstra's algorithm has a well-known extension called A* search, used in games and route planning. It adds a heuristic — an estimate of the remaining distance, such as the straight-line distance to the target — to the priority, so the search is guided toward the goal instead of expanding evenly in all directions. When the heuristic never overestimates the true remaining distance, A* is still guaranteed to find the shortest path, and it usually explores far fewer nodes than Dijkstra's algorithm. It is a good example of how extra information about the problem can make a general algorithm much faster.

When you need the shortest path between every pair of nodes, rather than from one start, the Floyd–Warshall algorithm is the tool. It keeps a table of best-known distances, initially the direct edges, and then considers each node in turn as a possible intermediate step, updating any pair whose route improves by going through it. The cost is O(V^3) time and O(V^2) space, so it suits small graphs — a few hundred nodes — where its simplicity wins. It also handles negative edges, and it detects negative cycles the same way Bellman-Ford does.

To see why Dijkstra's algorithm needs non-negative weights, construct the counterexample yourself. Take three nodes — A, B and C — with edges A to B costing 5, A to C costing 6, and C to B costing minus 4. Dijkstra's algorithm visits B first with a distance of 5 and marks it final, but the route through C costs only 2. The negative edge is what breaks the guarantee: a route discovered later can be cheaper than one found earlier, which can never happen when all weights are non-negative. Drawing the example takes a minute, and it makes the restriction feel like a fact about the world rather than a rule in a textbook.

Watch & Learn

One video to watch for this unit, from a trusted educator.

Key Terms

Weighted graph
A graph where each edge has a cost (weight), such as a distance, time or price.
Dijkstra's algorithm
Finds shortest paths from a start node when all edge weights are non-negative; O((V + E) log V) with a heap.
Relaxation
Improving a node's best-known distance by finding a shorter route through another node.
Priority queue (heap)
A structure that always yields the smallest item first; used by Dijkstra's algorithm to pick the next node.
Bellman-Ford algorithm
Finds shortest paths even with negative edge weights, in O(V × E) time; detects negative cycles.
Negative cycle
A loop whose total weight is negative, so distances can keep decreasing forever; then no shortest path exists.
Minimum spanning tree
The cheapest set of edges connecting all nodes of a graph, with no cycles.

Discussion Questions

  1. Why does Dijkstra's algorithm fail with negative edge weights? Construct a small example where it gives the wrong answer.
  2. How does Bellman-Ford detect a negative cycle? Why is one extra pass enough to find it?
  3. A puzzle has states and moves. How would you turn 'fewest moves to solve it' into a graph problem, and which algorithm would you use?

Practice Questions

  1. In the example, why is the shortest distance to B equal to 3 and not 4?
  2. Why does the code skip an entry when d != dist.get(node)?
  3. Which algorithm would you use if all edges weigh 1?
  4. What does Bellman-Ford do that Dijkstra's algorithm cannot?
  5. Why is there no shortest path in a graph with a negative cycle reachable from the start?
Show answers
  1. Because the route A → C → B costs 2 + 1 = 3, beating the direct edge A → B at 4. Dijkstra's algorithm discovers the cheaper route when it relaxes C's edges.
  2. Because a better distance for that node was found later, making this heap entry outdated. The heap can hold several entries per node; only the one matching the current best distance is processed.
  3. BFS. With equal weights, the fewest edges is the shortest path, and BFS finds it in O(V + E).
  4. It handles negative edge weights and detects negative cycles. It relaxes every edge V - 1 times, which is enough for any shortest path to propagate.
  5. Going round the cycle forever keeps reducing the distance without limit. The distance has no minimum, so 'shortest' is undefined.
Keep reading to complete this lesson