Lessons 11–15 · About 60 min per lesson

Weighted graphs and shortest paths

Choose an algorithm from the edge conditions and verify relaxations and unreachable nodes.

Lesson breakdown

  1. Lesson 11

    Store weights in adjacency lists and distinguish directed and undirected edges.

  2. Lesson 12

    Derive relaxation as an improvement of tentative distance through one edge.

  3. Lesson 13

    Implement Dijkstra with a min-heap for nonnegative weights.

  4. Lesson 14

    Skip stale heap entries and handle unreachable nodes and large distances.

  5. Lesson 15

    Track predecessors to recover a path and verify on a small graph.

Worked example

Edges A→B, A→C and C→B have weights 5, 2 and 1. What is the shortest distance from A to B?

How to solve it

B starts at 5 and C at 2. Processing C improves B to 3 via A→C→B.

Assignment

Implement single-source shortest paths on a nonnegative directed graph, printing -1 for unreachable nodes.

Check your result

B is at distance 3 in the example, an isolated D is reported as -1, and zero-weight edges work.