Lecture 9

Weighted Graphs

Shortest Path

If every weight had the same cost

Alt text

Properties

Property 1:

You could have a single course of shortest path

Dijkstra's Algorithm

Edge relaxation

Dijkstra's Algoithm

Algorithm DijkstraDistances(G, s): PQ <-new heap-based priority queue for all v <- G.vertices() if v = s setDistance(v, 0) else setDistance(v, (inf)) PQ.insert(getDistance(v), v) while !PQ.isEmpty() u <- PQ.removeMin() for all e in G.incidentEdges(u) { relax edge e } z <- G.opposite(u, e) r <- getDistance(u) + weight(e) if r < getDistance(z) setDistance(z, r) PQ.replaceKey(getLocator(z), r)

Analysis of Dijkstra's Algorithm

recall:

Why it Doesn’t Work for Negative-Weight Edges

Dijkstra’s algorithm is based on the greedy method

Alt text

Greedy Algorithm

Dijkstra example

DAG-Based algorithm

Algorithm DagDistances(G, s): for all v <- G.vertices() if v = s setDistance(v, 0) else setDistance(v, ) { Perform a topological sort of the vertices } for u <- 1 to n do {in topological order} for each e <- G.outEdges(u) { relax edge e } z <- G.opposite(u, e) r <- getDistance(u) + weight(e) if r < getDistance(z) setDistance(z, r)
init Label nodes with initial distances Topological sort visit in topological order result
Alt text Alt text Alt text Alt text Alt text

Downside of DAG Approach?

Minimum Spanning trees

Alt text

Aren't MST's = shortest path?

Cycle property

Alt text

Partition Property

Proof

Alt text

Prim-Jarnik’s Algorithm

KEY DIFFERENCE: Not trying to find the minimum distance, trying to find the minimum spanning tree

Alt text

Analysis

Recall:

Kruskal's Approach

Algorithm Kruskal(G) Input: a simple connected weighted graph G with n vertices and m edges Output: a minimum spanning tree T for G for each vertex v in G do define an elementary cluster C(v) = {v} Initialise a priority queue Q to contain all edges in G, using the weights as keys T -> null {T will ultimately contain the edges of the MST} while T has fewer than n-1 edges to (u,v) = value returned by Q.remove_min() (``find``) Let C(u) be the cluster containing u, and let C(v) be the cluster containing v if C(u) != C(v) then add edge (u,v) to T Merge C(u) and C(v) into one cluster (``union``) return tree T

Alt text

Data Structure for Krukal's Approach

List-based partition

Partition-base implementation

Solving Graph problems

Extension Material

NONE OF THIS WILL APPEAR ON THE FINAL EXAM

Transitive Closure

Computing Transitive Closure

Dynamic Programming

Floyd-Warshall Algorithm

iteration 0 iteration 1 iteration 2 iteration 3
Alt text Alt text Alt text Alt text

All pairs shortest paths

Joels insights: