CAP7004 · Unit 6: Graphs
Dijkstra shortest paths
8 practice questions
Key points
- Greedy; needs non-negative weights
- O((V+E) log V) with a binary heap
- Relax: dist[v] = min(dist[v], dist[u] + w)
- Negative edges need Bellman-Ford
Dijkstra's algorithm finds the shortest path from one source to all vertices in a graph with non-negative edge weights. It is greedy: repeatedly take the unvisited vertex with the smallest known distance and relax its outgoing edges (dist[v] = min(dist[v], dist[u] + w)).
def dijkstra(g, s):
dist = {u: float("inf") for u in g}; dist[s] = 0
pq = [(0, s)]
while pq:
d, u = heapq.heappop(pq)
if d > dist[u]: continue # stale entry
for v, w in g[u]:
if d + w < dist[v]:
dist[v] = d + w
heapq.heappush(pq, (d + w, v))
return dist
Complexity: O((V + E) log V) with a binary heap and adjacency list; O(V^2) with an array and no heap.
Worked example: edges A-B 4, A-C 1, C-B 2, B-D 1, C-D 5 from A give distances A 0, C 1, B 3, D 4; the shortest route to D is A -> C -> B -> D.
Limits: it is not correct with negative weights (use Bellman-Ford). Example: A->B 2, A->C 5, C->B -10; the standard version, which finalises each vertex once, reports dist(B) = 2 but the true shortest is -5. Variants that re-relax vertices can recover on small cases but lose the guarantee and the speed. For unweighted graphs BFS is enough.
Exam pitfall: Dijkstra gives shortest weighted paths; the path with fewest edges may not be the cheapest.
Try two questions
For an unweighted graph the simplest correct shortest-path method is:
- Kruskal
- Dijkstra with a heap
- Heap sort
- BFS
Show the answer
D. BFS already counts edges level by level in O(V + E).
Which data structure makes Dijkstra efficient on sparse graphs?
- A plain FIFO queue
- A hash set used alone
- A min-heap priority queue
- A stack of vertices
Show the answer
C. The heap yields the closest unfinished vertex in O(log V).