EECS 311: Chapter 9 Notes Chris Riesbeck EECS Northwestern
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] known[v] = true For all unknown successors w of v cvw = cost[v] + weight[v, w] If cvw < cost[w] cost[w] = cvw path[w] = v push w onto pq
Calculating All Cheapest Paths 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] + cost[k, v] If ck < cost[u, v] cost[u, v] = ck path[u, v] = k
Minimum Spanning Tree Example Graphs can have more than one MST but in this case, there's just this one. Note: Undirected graph.
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] known[v] = true For all unknown successors w of v If weight[v, w] < cost[w] cost[w] = weight[v, w] path[w] = v push w onto pq Same as Dijkstra's algorithm except for what goes in cost[]
Kruskal's Algorithm To find the Minimum Spanning Tree: Set MST to an empty list of edges. Put all edges in priority queue pq that percolates cheapest edges to the top. Set ds to the set of singleton sets of all vertices. While pq not empty Pop edge from pq. If find(u) ≠ find(v) union(u, v) in ds. Add edge to MST. Cheap check to avoid cycles in MST. Edges need not be connected. A forest of trees is created.