Single Source Shortest Path

Week 14, Wednesday — Dijkstra’s

April 10, 2026

Announcements

Single Source Shortest Path

Given a start vertex (source) \(s\), find the path of least total cost from \(s\) to every vertex in the graph.

Single Source Shortest Path

  • Input: directed graph \(G\) with non-negative edge weights, and a start vertex \(s\).
  • Output: A subgraph \(G’\) consisting of the shortest (minimum total cost) paths from \(s\) to every other vertex in the graph.

Dijkstra’s Algorithm (1959)

 

Note:

SSSP Algorithm

Given a source vertex \(s\), we wish to find the shortest path from \(s\) to every other vertex in the graph.

  1. Initialize structure:

    • d:
    • p:
  2. Repeat these steps:

    • Label a new (unlabelled) vertex \(v\), whose shortest distance has been found
    • Update \(v\)’s neighbors with improved distance and predecessor

SSSP Algorithm

  1. Initialize structure:

    • For all v: d[v] = INF, p[v] = null
    • Let d[s] = 0
    • Initialize PQ by d[v]
  2. Repeat n times:

    • Remove minimum d[] unlabelled vertex: v
    • Label vertex v
    • For all unlabelled neighbors w of v:
      • If (________________ < d[w])
        • d[w] = ________________
        • p[w] = v
  3. Return p

Three Observations:

  • When a node becomes labeled, its shortest distance is final. It will never improve again.

  • d[] values only decrease, never increase.

  • The predecessors p[] form a shortest-path tree.

Your Turn

Execute Dijkstra’s algorithm on this graph:

Prim’s Algorithm: Runtime Analysis

  1. Initialize structure:

    • For all v: d[v] = INF, p[v] = null
    • Let d[s] = 0
    • Initialize PQ by d[v]
  2. Repeat n times:

    • Remove minimum d[] unlabelled vertex: v
    • Label vertex v
    • For all unlabelled neighbors w of v: 💜
      • If (wt[(v,w)] < d[w])
        • d[w] = wt[(v,w)]
        • p[w] = v
  3. Return p

\(n\) removeMins + \(\leq m\) decreaseKeys
💜 \(O(m)\) total (adj list)  |  \(O(n^2)\) total (adj matrix)

Adj matrix Adj list
heap \(O(n^2 + m \log n)\) \(O(m \log n)\)
unsorted array \(O(n^2)\) \(O(n^2)\)

 

Which is best? Depends on graph density:

  • Sparse (\(m=O(n)\)):
  • Dense (\(m=O(n^2)\)):

The End.

Thanks for a fun year!