EECS 311 Chapter 9 Notes Chris Riesbeck EECS
EECS 311: Chapter 9 Notes Chris Riesbeck EECS Northwestern
o Unless otherwise noted, all tables, graphs and code from Mark Allen Weiss' Data Structures and Algorithm Analysis in C++, 3 rd ed, copyright © 2006 by Pearson Education, Inc.
Cheapest Path Example
Dijkstra's Algorithm To find cheapest path from vertex s to vertex e: For all v cost[v] = ∞; known[v] = false; path[v] = cost[s] = 0 Push s onto a priority queue pq that percolates vertices with lowest cost[] to the top. While pq not empty Pop v from pq If v = e, done. If not known[v] = true For all unknown successors w of v cvw = cost[v] + weight[v, w] If cvw < cost[w] = cvw path[w] = v push w onto pq
Calculating All Cheapest Paths o o Dijkstra's algorithm is |V|2 to find all cheapest paths between 2 vertices. To use it find all cheapest paths would be |V|4. Floyd's algorithm can do it in |V|3. Floyd's algorithm is simple. Complexity easy to determine. Why it works is not so obvious.
Floyd's Algorithm To find cheapest paths for all {u, v} in G: For all u, v in G cost[u, v] = weight[u, v]; path[u, v] = - For every vertex k For every vertex u For every vertex v ck = cost[u, k] If ck < cost[u, v] = path[u, v] = + cost[k, v] v] ck k
Minimum Spanning Tree Example Note: Undirected graph. Graphs can have more than one MST but in this case, there's just this one.
Prim's Algorithm To find the Minimum Spanning Tree: For all v cost[v] = ∞; known[v] = false; path[v] = cost[s] = 0 Push s onto a priority queue pq that percolates vertices with lowest cost[] to the top. While pq not empty Pop v from pq If not known[v] = true For all unknown successors w of v If weight[v, w] < cost[w] Same as Dijkstra's cost[w] = weight[v, w] algorithm except for path[w] = v what goes in cost[] push w onto pq
Kruskal's Algorithm To find the Minimum Spanning Tree: Set MST to an empty list of edges. Put all edges <u, v, weight> in priority queue pq that percolates Edges need not cheapest edges to the top. be connected. A Set ds to the set of singleton forest setsof of trees is created. all vertices. While pq not empty Pop edge <u, v, weight> from pq. If find(u) ≠ find(v) Cheap check to avoid union(u, v) in ds. cycles in MST. Add edge to MST.
- Slides: 9