Depth-First Search; Dijkstra’s Shortest Paths
Announcements
Today:
Labels every vertex, and labels every edge discovery or back.
The discovery edges form a ________________________.
If \((u, w)\) is a back edge, then \(w\) is __________________________ of \(u\).
To find a path from \(A\) to \(v\): _____________________________.
Is it a shortest path? ____________________
Number of connected components: __________________________
\(G\) has a cycle exactly when ______________________________
For directed graphs, a timer before and after the for loop (pre and post)
gives more: topological sort, strongly connected components, and cycle detection.
\(n\) vertices, \(m\) edges, \(c\) connected components.
Traverse every component (BFS or DFS).
How many discovery edges are there?
How many non-discovery edges?
Using only \(n\), \(m\), and \(c\): when is the graph acyclic?
Try it: \(n = 12\), \(m = 13\), \(c = 3\).
\(n\) vertices, \(m\) edges.
Labelling vertices: ________
Labelling edges: ________
for all w in G.adjacentVertices(v):
| Adjacency list | Adjacency matrix | |
|---|---|---|
| one vertex v | ||
| summed over all v | ||
| Total |
Given a start vertex (source) \(s\), find the path of least total cost
from \(s\) to every vertex in the graph.

Dijkstra’s Algorithm (1959)
Note:
Once a vertex is labelled, its distance is final.
d[] values only decrease, never increase.
The predecessors p[] form a shortest-path tree.

| Adj matrix | Adj list | |
|---|---|---|
| heap | O(n2 + m log n) | O(n log n + m log n) |
| unsorted array | O(n2) | O(n2) |
Which is best? Depends on the graph’s density:
Friday: minimum spanning trees.
Monday: Kruskal’s algorithm.
Examlet 9 Thursday to Sunday.
After class: run Dijkstra’s algorithm from A.

CPSC 221