Data Structures Graphs Graph ADT Not quite an














































































































- Slides: 110
Data Structures Graphs
Graph… ADT? • Not quite an ADT… operations not clear • A formalism for representing relationships between objects Graph G = (V, E) – Set of vertices: V = {v 1, v 2, …, vn} – Set of edges: E = {e 1, e 2, …, em} where each ei connects two vertices (vi 1, vi 2) Han Luke Leia V = {Han, Leia, Luke} E = {(Luke, Leia), (Han, Leia), (Leia, Han)} 2
Examples of Graphs • The web – Vertices are webpages – Each edge is a link from one page to another • Call graph of a program – Vertices are subroutines – Edges are calls and returns • Social networks – Vertices are people – Edges connect friends 3
Graph Definitions In directed graphs, edges have a direction: Han Luke Leia In undirected graphs, they don’t (are two-way): Han Luke v is adjacent to u if (u, v)Leia E 4
Weighted Graphs Each edge has an associated weight or cost. Clinton 20 Mukilteo Kingston 30 Bainbridge 35 Edmonds Seattle 60 Bremerton 5
Paths and Cycles • A path is a list of vertices {v 1, v 2, …, vn} such that (vi, vi+1) E for all 0 i < n. • A cycle is a path that begins and ends at the same node. Chicago Seattle Salt Lake City San Francisco Dallas • p = {Seattle, Salt Lake City, Chicago, Dallas, San Francisco, Seattle} 6
Path Length and Cost • Path length: the number of edges in the path • Path cost: the sum of the costs of each edge Chicago 3. 5 Seattle 2 2 2 Salt Lake City 2. 5 3 San Francisco Dallas length(p) = 5 cost(p) = 11. 5 7
More Definitions: Simple Paths and Cycles A simple path repeats no vertices (except that the first can also be the last): p = {Seattle, Salt Lake City, San Francisco, Dallas} p = {Seattle, Salt Lake City, Dallas, San Francisco, Seattle} A cycle is a path that starts and ends at the same node: p = {Seattle, Salt Lake City, Dallas, San Francisco, Seattle} p = {Seattle, Salt Lake City, Seattle, San Francisco, Seattle} A simple cycle is a cycle that is also a simple path (in undirected graphs, no edge can be repeated) 8
Trees as Graphs • Every tree is a graph with some restrictions: – the tree is directed – there are no cycles (directed or undirected) – there is a directed path from the root to every node A B D C E G F H 9
Directed Acyclic Graphs (DAGs) DAGs are directed graphs with no (directed) cycles. main() mult() Aside: If program callgraph is a DAG, then all procedure calls can be inlined add() access() read() 10
Rep 1: Adjacency Matrix A |V| x |V| array in which an element (u, v) is true if and only if there is an edge from u to v Han Luke Leia Runtimes: Iterate over vertices? Iterate over edges? Iterate edges adj. to vertex? Existence of edge? Han Luke Leia Space requirements? 11
Rep 2: Adjacency List A |V|-ary list (array) in which each entry stores a list (linked list) of all adjacent vertices Han Luke Leia Runtimes: Iterate over vertices? Iterate over edges? Iterate edges adj. to vertex? Existence of edge? Han Luke Leia Space requirements? 12
Some Applications: Moving Around Washington What’s the shortest way to get from Seattle to Pullman? Edge labels: 13
Some Applications: Moving Around Washington What’s the fastest way to get from Seattle to Pullman? Edge labels: 14
Some Applications: Reliability of Communication If Wenatchee’s phone exchange goes down, can Seattle still talk to Pullman? 15
Some Applications: Bus Routes in Downtown Seattle If we’re at 3 rd and Pine, how can we get to 1 st and University using Metro? How about 4 th and Seneca? 16
Application: Topological Sort Given a directed graph, G = (V, E), output all the vertices in V such that no vertex is output before any other vertex with an edge to it. CSE 321 CSE 142 CSE 143 CSE 341 CSE 322 CSE 326 CSE 403 CSE 421 CSE 451 CSE 370 CSE 378 CSE 467 Is the output unique? 17
Topological Sort: Take One 1. Label each vertex with its in-degree (# of inbound edges) 2. While there are vertices remaining: a. Choose a vertex v of in-degree zero; output v b. Reduce the in-degree of all vertices adjacent to v c. Remove v from the list of vertices Runtime: 18
void Graph: : topsort(){ Vertex v, w; label. Each. Vertex. With. Its. In-degree(); for (int counter=0; counter < NUM_VERTICES; counter++){ v = find. New. Vertex. Of. Degree. Zero(); v. topological. Num = counter; for each w adjacent to v w. indegree--; } } 19
Topological Sort: Take Two 1. Label each vertex with its in-degree 2. Initialize a queue Q to contain all in-degree zero vertices 3. While Q not empty a. v = Q. dequeue; output v b. Reduce the in-degree of all vertices adjacent to v c. If new in-degree of any such vertex u is zero Q. enqueue(u) Runtime: Note: could use a stack, list, set, box, … instead of a queue 20
void Graph: : topsort(){ Queue q(NUM_VERTICES); int counter = 0; Vertex v, w; label. Each. Vertex. With. Its. In-degree(); q. make. Empty(); for each vertex v if (v. indegree == 0) q. enqueue(v); intialize the queue while (!q. is. Empty()){ get a vertex with indegree 0 v = q. dequeue(); v. topological. Num = ++counter; for each w adjacent to v insert new if (--w. indegree == 0) eligible q. enqueue(w); vertices } } Runtime: 21
Graph Connectivity Undirected graphs are connected if there is a path between any two vertices Directed graphs are strongly connected if there is a path from any one vertex to any other Directed graphs are weakly connected if there is a path between any two vertices, ignoring direction A complete graph has an edge between every pair of vertices 22
Graph Traversals • Breadth-first search (and depth-first search) work for arbitrary (directed or undirected) graphs - not just mazes! – Must mark visited vertices so you do not go into an infinite loop! • Either can be used to determine connectivity: – Is there a path between two given vertices? – Is the graph (weakly) connected? • Which one: – Uses a queue? – Uses a stack? – Always finds the shortest path (for unweighted graphs)? 23
CSE 326: Data Structures Graph Traversals James Fogarty Autumn 2007
Graph Connectivity • Undirected graphs are connected if there is a path between any two vertices • Directed graphs are strongly connected if there is a path from any one vertex to any other • Directed graphs are weakly connected if there is a path between any two vertices, ignoring direction • A complete graph has an edge between every pair of vertices 25
Graph Traversals • Breadth-first search (and depth-first search) work for arbitrary (directed or undirected) graphs - not just mazes! – Must mark visited vertices. Why? – So you do not go into an infinite loop! It’s not a tree. • Either can be used to determine connectivity: – Is there a path between two given vertices? – Is the graph (weakly/strongly) connected? • Which one: – Uses a queue? – Uses a stack? – Always finds the shortest path (for unweighted graphs)? 26
The Shortest Path Problem • Given a graph G, edge costs ci, j, and vertices s and t in G, find the shortest path from s to t. • For a path p = v 0 v 1 v 2 … vk – unweighted length of path p = k (a. k. a. length) – weighted length of path p = i=0. . k-1 ci, i+1 (a. k. a cost) – Path length equals path cost when ? 27
Single Source Shortest Paths (SSSP) • Given a graph G, edge costs ci, j, and vertex s, find the shortest paths from s to all vertices in G. – Is this harder or easier than the previous problem? 28
All Pairs Shortest Paths (APSP) • Given a graph G and edge costs ci, j, find the shortest paths between all pairs of vertices in G. – Is this harder or easier than SSSP? – Could we use SSSP as a subroutine to solve this? 29
Depth-First Graph Search Open – Stack Criteria – Pop • DFS( Start, Goal_test) • push(Start, Open); • repeat • if (empty(Open)) then return fail; • Node : = pop(Open); • if (Goal_test(Node)) then return Node; • for each Child of node do • if (Child not already visited) then push(Child, Open); • Mark Node as visited; • end 30
Breadth-First Graph Search Open – Queue Criteria – Dequeue (FIFO) • BFS( Start, Goal_test) • enqueue(Start, Open); • repeat • if (empty(Open)) then return fail; • Node : = dequeue(Open); • if (Goal_test(Node)) then return Node; • for each Child of node do • if (Child not already visited) then enqueue(Child, Open); • Mark Node as visited; • end 31
Comparison: DFS versus BFS • Depth-first search –Does not always find shortest paths –Must be careful to mark visited vertices, or you could go into an infinite loop if there is a cycle • Breadth-first search –Always finds shortest paths – optimal solutions –Marking visited nodes can improve efficiency, but even without doing so search is guaranteed to terminate –Is BFS always preferable? 32
DFS Space Requirements • Assume: – Longest path in graph is length d – Highest number of out-edges is k • DFS stack grows at most to size dk – For k=10, d=15, size is 150 33
BFS Space Requirements • Assume – Distance from start to a goal is d – Highest number of out edges is k BFS • Queue could grow to size kd – For k=10, d=15, size is 1, 000, 000 34
Conclusion • For large graphs, DFS is hugely more memory efficient, if we can limit the maximum path length to some fixed d. – If we knew the distance from the start to the goal in advance, we can just not add any children to stack after level d – But what if we don’t know d in advance? 35
Iterative-Deepening DFS (I) • Bounded_DFS(Start, Goal_test, Limit) • Start. dist = 0; • push(Start, Open); • repeat • if (empty(Open)) then return fail; • Node : = pop(Open); • if (Goal_test(Node)) then return Node; • if (Node. dist Limit) then return fail; • for each Child of node do • if (Child not already i-visited) then • Child. dist : = Node. dist + 1; • push(Child, Open); • Mark Node as i-visited; • end 36
Iterative-Deepening DFS (II) • IDFS_Search(Start, Goal_test) • i : = 1; • repeat • answer : = Bounded_DFS(Start, Goal_test, i); • if (answer != fail) then return answer; • i : = i+1; • end 37
Analysis of IDFS • Work performed with limit < actual distance to G is wasted – but the wasted work is usually small compared to amount of work done during the last iteration Ignore low order terms! Same time complexity as BFS Same space complexity as (bounded) DFS 38
Saving the Path • Our pseudocode returns the goal node found, but not the path to it • How can we remember the path? – Add a field to each node, that points to the previous node along the path – Follow pointers from goal back to start to recover path 39
Example Seattle Salt Lake City San Francisco Dallas 40
Example (Unweighted Graph) Seattle Salt Lake City San Francisco Dallas 41
Example (Unweighted Graph) Seattle Salt Lake City San Francisco Dallas 42
Graph Search, Saving Path • Search( Start, Goal_test, Criteria) • insert(Start, Open); • repeat • if (empty(Open)) then return fail; • select Node from Open using Criteria; • if (Goal_test(Node)) then return Node; • for each Child of node do • if (Child not already visited) then • Child. previous : = Node; • Insert( Child, Open ); • Mark Node as visited; • end 43
Weighted SSSP: The Quest For Food Home Ben & Jerry’s Cedars Neelam’s 285 70 75 U Village 365 25 350 25 35 Café Allegro Schultzy’s 15, 356 350 10 ALLEN Delfino’s 375 Coke Closet The Ave 40 35 HUB 15 Vending Machine in EE 1 Parent’s Home Can we calculate shortest distance to all nodes from Allen Center? 44
Weighted SSSP: The Quest For Food Home Ben & Jerry’s Cedars Neelam’s 285 70 75 U Village 365 25 35 Café Allegro Schultzy’s 15, 356 350 10 ALLEN Delfino’s 375 Coke Closet The Ave 40 35 HUB 15 Vending Machine in EE 1 Parent’s Home Can we calculate shortest distance to all nodes from Allen Center? 45
Edsger Wybe Dijkstra (1930 -2002) • Invented concepts of structured programming, synchronization, weakest precondition, and "semaphores" for controlling computer processes. The Oxford English Dictionary cites his use of the words "vector" and "stack" in a computing context. • Believed programming should be taught without computers • 1972 Turing Award • “In their capacity as a tool, computers will be but a ripple on the surface of our culture. In their capacity as intellectual challenge, they are without precedent in the cultural history of mankind. ” 46
General Graph Search Algorithm Open – some data structure (e. g. , stack, queue, heap) Criteria – some method for removing an element from Open • Search( Start, Goal_test, Criteria) • insert(Start, Open); • repeat • if (empty(Open)) then return fail; • select Node from Open using Criteria; • if (Goal_test(Node)) then return Node; • for each Child of node do • if (Child not already visited) then Insert( Child, Open ); • Mark Node as visited; • end 47
Shortest Path for Weighted Graphs • Given a graph G = (V, E) with edge costs c(e), and a vertex s V, find the shortest (lowest cost) path from s to every vertex in V • Assume: only positive edge costs 48
Dijkstra’s Algorithm for Single Source Shortest Path • Similar to breadth-first search, but uses a heap instead of a queue: – Always select (expand) the vertex that has a lowest-cost path to the start vertex • Correctly handles the case where the lowest-cost (shortest) path to a vertex is not the one with fewest edges 49
CSE 326: Data Structures Dijkstra’s Algorithm
Dijkstra, Edsger Wybe Legendary figure in computer science; was a professor at University of Texas. Supported teaching introductory computer courses without computers (pencil and paper programming) Supposedly wouldn’t (until very late in life) read his e-mail; so, his staff had to print out messages and put them in his box. E. W. Dijkstra (1930 -2002) 1972 Turning Award Winner, Programming Languages, semaphores, and … 51
Dijkstra’s Algorithm: Idea Adapt BFS to handle weighted graphs Two kinds of vertices: – – Finished or known vertices • Shortest distance has been computed Unknown vertices • Have tentative distance 52
Dijkstra’s Algorithm: Idea At each step: 1) Pick closest unknown vertex 2) Add it to known vertices 3) Update distances 53
Dijkstra’s Algorithm: Pseudocode Initialize the cost of each node to Initialize the cost of the source to 0 While there are unknown nodes left in the graph Select an unknown node b with the lowest cost Mark b as known For each node a adjacent to b a’s cost = min(a’s old cost, b’s cost + cost of (b, a)) a’s prev path node = b 54
Important Features • Once a vertex is made known, the cost of the shortest path to that node is known • While a vertex is still not known, another shorter path to it might still be found • The shortest path itself can found by following the backward pointers stored in node. path 55
Dijkstra’s Algorithm in action 0 B 2 A 2 F 10 2 1 4 9 2 D E 7 Vertex Visited? Cost A 0 B ? ? C ? ? D ? ? E ? ? F ? ? G ? ? H ? ? 3 1 G 3 C 11 H 1 Found by 56
Dijkstra’s Algorithm in action 0 2 B 2 A 2 F 10 2 1 4 9 C 1 2 4 D E 7 Vertex Visited? Cost A Y 0 3 1 G 3 11 H 1 Found by B <=2 A C <=1 A D <=4 A E ? ? F ? ? G ? ? H ? ? 57
Dijkstra’s Algorithm in action 0 2 B 2 A 2 F 10 2 1 4 9 C 1 2 4 D E 7 Vertex Visited? Cost A Y 0 B 3 1 G 3 11 12 1 Found by <=2 A 1 A D <=4 A E <=12 C F ? ? G ? ? H ? ? C Y H 58
Dijkstra’s Algorithm in action 0 2 B 2 A 2 4 F 10 2 1 4 9 C 1 2 4 D E 7 3 1 G 3 11 H 12 1 Vertex Visited? Cost Found by A Y 0 B Y 2 A C Y 1 A D <=4 A E <=12 C F <=4 B G ? ? H ? ? 59
Dijkstra’s Algorithm in action 0 2 B 2 A 2 4 F 10 2 1 4 9 C 1 2 4 D E 7 3 1 G 3 11 H 12 1 Vertex Visited? Cost Found by A Y 0 B Y 2 A C Y 1 A D Y 4 A E <=12 C F <=4 B G ? ? H ? ? 60
Dijkstra’s Algorithm in action 0 2 B 2 A 2 4 F 10 2 1 4 9 C 1 2 4 D E 7 3 1 G 3 11 12 1 Vertex Visited? Cost A Y 0 B Y 2 A C Y 1 A D Y 4 A <=12 C 4 B E F Y G ? ? H <=7 7 H Found by F 61
Dijkstra’s Algorithm in action 0 2 B 2 A 2 4 F 10 2 1 4 9 C 1 2 4 D E 7 3 1 G 8 3 11 12 1 Vertex Visited? Cost A Y 0 B Y 2 A C Y 1 A D Y 4 A <=12 C 4 B <=8 H 7 F E F Y G H Y 7 H Found by 62
Dijkstra’s Algorithm in action 0 2 B 2 A 2 4 F 10 2 1 4 9 C 1 2 4 D E 7 3 1 G 8 3 11 11 1 Vertex Visited? Cost A Y 0 B Y 2 A C Y 1 A D Y 4 A <=11 G E 7 H Found by F Y 4 B G Y 8 H H Y 7 F 63
Dijkstra’s Algorithm in action 0 2 B 2 A 2 4 F 10 2 1 4 9 C 1 2 4 D E 7 3 1 G 8 3 11 7 H 11 1 Vertex Visited? Cost Found by A Y 0 B Y 2 A C Y 1 A D Y 4 A E Y 11 G F Y 4 B G Y 8 H H Y 7 F 64
Your turn 1 v 2 2 v 0 5 1 2 V v 1 2 s v 0 1 v 3 6 v 4 5 Visited? Cost Found by v 5 1 3 10 v 6 v 1 v 2 v 3 v 4 v 5 v 6 65
Dijkstra’s Alg: Implementation Initialize the cost of each node to Initialize the cost of the source to 0 While there are unknown nodes left in the graph Select the unknown node b with the lowest cost Mark b as known For each node a adjacent to b a’s cost = min(a’s old cost, b’s cost + cost of (b, a)) a’s prev path node = b (if we updated a’s cost) What data structures should we use? Running time? 67
void Graph: : dijkstra(Vertex s){ Vertex v, w; Initialize s. dist = 0 and set dist of all other vertices to infinity while (there exist unknown vertices, find the one b with the smallest distance) b. known = true; Sounds like delete. Min on a for each a adjacent to b heap… if (!a. known) Sounds like if (b. dist + weight(b, a) < a. dist){ adjacency a. dist = (b. dist + weight(b, a)); lists a. path = b; Sounds like } decrease. Key } } Running time: O(|E| log |V|) – there are |E| edges to examine, and each one causes a heap operation of time O(log |V|) 68
Dijkstra’s Algorithm: Summary • Classic algorithm for solving SSSP in weighted graphs without negative weights • A greedy algorithm (irrevocably makes decisions without considering future consequences) • Intuition for correctness: – – shortest path from source vertex to itself is 0 cost of going to adjacent nodes is at most edge weights cheapest of these must be shortest path to that node update paths for new node and continue picking cheapest path 69
Correctness: The Cloud Proof Next shortest path from inside the known cloud V Better path to V? No! The Known Cloud W Source How does Dijkstra’s decide which vertex to add to the Known set next? • If path to V is shortest, path to W must be at least as long (or else we would have picked W as the next vertex) 70 • So the path through W to V cannot be any shorter!
Correctness: Inside the Cloud Prove by induction on # of nodes in the cloud: Initial cloud is just the source with shortest path 0 Assume: Everything inside the cloud has the correct shortest path Inductive step: Only when we prove the shortest path to some node v (which is not in the cloud) is correct, we add it to the cloud When does Dijkstra’s algorithm not work? 71
The Trouble with Negative Weight Cycles 2 A -5 C B 10 1 2 E D What’s the shortest path from A to E? Problem? 72
Dijkstra’s vs BFS At each step: 1) Pick closest unknown vertex 2) Add it to finished vertices 3) Update distances Dijkstra’s Algorithm At each step: 1) Pick vertex from queue 2) Add it to visited vertices 3) Update queue with neighbors Breadth-first Search Some Similarities: 73
Single-Source Shortest Path • Given a graph G = (V, E) and a single distinguished vertex s, find the shortest weighted path from s to every other vertex in G. All-Pairs Shortest Path: • Find the shortest paths between all pairs of vertices in the graph. • How? 74
Analysis • Total running time for Dijkstra’s: O(|V| log |V| + |E| log |V|) (heaps) What if we want to find the shortest path from each point to ALL other points? 75
Dynamic Programming Algorithmic technique that systematically records the answers to sub-problems in a table and re-uses those recorded results (rather than re-computing them). Simple Example: Calculating the Nth Fibonacci number. Fib(N) = Fib(N-1) + Fib(N-2) 76
Floyd-Warshall for (int k = 1; k =< V; k++) for (int i = 1; i =< V; i++) for (int j = 1; j =< V; j++) if ( ( M[i][k]+ M[k][j] ) < M[i][j] ) M[i][j] = M[i][k]+ M[k][j] Invariant: After the kth iteration, the matrix includes the shortest paths for all pairs of vertices (i, j) containing only vertices 1. . k as intermediate vertices 77
2 a Initial state of the matrix: 1 -4 b b c d e a 0 2 - -4 - b - 0 -2 1 3 c - - 0 - 1 d - - - 0 4 e - - 0 c 3 d a -2 4 M[i][j] = min(M[i][j], M[i][k]+ M[k][j]) e 1 78
2 a Floyd-Warshall for All-pairs shortest path 1 -4 d 4 a b c d e a 0 2 0 -4 0 b - 0 -2 1 -1 c - - 0 - 1 d - - - 0 4 e - - 0 b -2 c 3 e 1 Final Matrix Contents 79
CSE 326: Data Structures Spanning Trees
A Hidden Tree Start End 81
Spanning Tree in a Graph Vertex = router Edge = link between routers Spanning tree - Connects all the vertices - No cycles 82
Undirected Graph • G = (V, E) – V is a set of vertices (or nodes) – E is a set of unordered pairs of vertices 2 1 3 V = {1, 2, 3, 4, 5, 6, 7} E = {{1, 2}, {1, 6}, {1, 5}, {2, 7}, {2, 3}, {3, 4}, {4, 7}, {4, 5}, {5, 6}} 4 2 and 3 are adjacent 2 is incident to edge {2, 3} 7 6 5 83
Spanning Tree Problem • Input: An undirected graph G = (V, E). G is connected. • Output: T contained in E such that – (V, T) is a connected graph – (V, T) has no cycles 84
Spanning Tree Algorithm ST(i: vertex) mark i; for each j adjacent to i do if j is unmarked then Add {i, j} to T; ST(j); end{ST} Main T : = empty set; ST(1); end{Main} 85
Example of Depth First Search ST(1) 2 1 3 7 4 6 5 86
Example Step 16 ST(1) 2 1 3 7 4 6 5 {1, 2} {2, 7} {7, 5} {5, 4} {4, 3} {5, 6} 87
Minimum Spanning Trees Given an undirected graph G=(V, E), find a graph G’=(V, E’) such that: – E’ is a subset of E – |E’| = |V| - 1 – G’ is connected – is minimal G’ is a minimum spanning tree. Applications: wiring a house, power grids, Internet connections 88
Minimum Spanning Tree Problem • Input: Undirected Graph G = (V, E) and a cost function C from E to the reals. C(e) is the cost of edge e. • Output: A spanning tree T with minimum total cost. That is: T that minimizes 89
Best Spanning Tree • Each edge has the probability that it won’t fail • Find the spanning tree that is least likely to fail 2 1 . 80 . 75 3 . 95 7 . 50 1. 0 . 95. 89 6 . 85 . 84 4 5. 80 90
Example of a Spanning Tree 2 1 . 80 . 75 3 . 95 7 . 50 1. 0 . 95. 89 6 . 85 . 84 4 5. 80 Probability of success =. 85 x. 95 x. 89 x. 95 x 1. 0 x. 84 =. 5735 91
Minimum Spanning Tree Problem • Input: Undirected Graph G = (V, E) and a cost function C from E to the reals. C(e) is the cost of edge e. • Output: A spanning tree T with minimum total cost. That is: T that minimizes 92
Reducing Best to Minimum Let P(e) be the probability that an edge doesn’t fail. Define: Minimizing is equivalent to maximizing because 93
Example of Reduction 1 2 . 80 . 75 3 . 097 1 2 . 95 7 . 50 . 022 1. 0 . 95. 89 6 . 85 . 125 3 . 84 4 5. 80 Best Spanning Tree Problem . 301 7. 022 . 000. 051 6 . 071 . 076 4 5. 097 Minimum Spanning Tree Problem 94
Find the MST 4 7 9 1 2 5 95
Find the MST 1 A B 7 H 5 3 2 11 12 9 C 10 D 6 F 13 4 G 4 E 96
Two Different Approaches Prim’s Algorithm Kruskals’s Algorithm Looks familiar! Completely different! 97
Prim’s algorithm Idea: Grow a tree by adding an edge from the “known” vertices to the “unknown” vertices. Pick the edge with the smallest weight. G v known 98
Prim’s Algorithm for MST A node-based greedy algorithm Builds MST by greedily adding nodes 1. Select a node to be the “root” • mark it as known • Update cost of all its neighbors 2. While there are unknown nodes left in the graph a. Select an unknown node b with the smallest cost from some known node a b. Mark b as known c. Add (a, b) to MST d. Update cost of all nodes adjacent to b 99
Your Turn Start with V 1 Find MST using Prim’s V v 1 v 2 v 3 v 4 v 5 v 6 v 7 3 1 4 2 v 3 Kwn Distance path v 2 2 v 1 5 7 v 4 8 v 6 10 v 5 4 6 1 v 7 Order Declared Known: V 1 100
Prim’s Algorithm Analysis Running time: Same as Dijkstra’s: O(|E| log |V|) Correctness: Proof is similar to Dijkstra’s 101
Kruskal’s MST Algorithm Idea: Grow a forest out of edges that do not create a cycle. Pick an edge with the smallest weight. G=(V, E) v 102
Kruskal’s Algorithm for MST An edge-based greedy algorithm Builds MST by greedily adding edges 1. Initialize with • empty MST • all vertices marked unconnected • all edges unmarked 2. While there are still unmarked edges a. Pick the lowest cost edge (u, v) and mark it b. If u and v are not already connected, add (u, v) to the MST and mark u and v as connected to each other Doesn’t it sound familiar? 103
Example of Kruskal 1 1 1 3 2 3 3 4 7 3 1 6 2 5 3 0 4 2 {7, 4} {2, 1} {7, 5} {5, 6} {5, 4} {1, 6} {2, 7} {2, 3} {3, 4} {1, 5} 0 1 1 2 2 3 3 4 104
Data Structures for Kruskal • Sorted edge list {7, 4} {2, 1} {7, 5} {5, 6} {5, 4} {1, 6} {2, 7} {2, 3} {3, 4} {1, 5} 0 1 1 2 2 3 3 4 • Disjoint Union / Find – Union(a, b) - union the disjoint sets named by a and b – Find(a) returns the name of the set containing a 105
Example of DU/F 1 1 3 7 2 3 3 3 4 7 3 2 5 3 0 1 6 Find(5) = 7 Find(4) = 7 4 2 {7, 4} {2, 1} {7, 5} {5, 6} {5, 4} {1, 6} {2, 7} {2, 3} {3, 4} {1, 5} 0 1 1 2 2 3 3 4 106
Example of DU/F 2 1 1 1 3 7 2 Find(1) = 1 3 Find(6) = 7 3 3 4 7 3 1 6 2 5 3 0 4 2 {7, 4} {2, 1} {7, 5} {5, 6} {5, 4} {1, 6} {2, 7} {2, 3} {3, 4} {1, 5} 0 1 1 2 2 3 3 4 107
Example of DU/F 3 Union(1, 7) 1 1 3 7 2 3 3 3 4 7 3 1 6 2 5 3 0 4 2 {7, 4} {2, 1} {7, 5} {5, 6} {5, 4} {1, 6} {2, 7} {2, 3} {3, 4} {1, 5} 0 1 1 2 2 3 3 4 108
Kruskal’s Algorithm with DU / F Sort the edges by increasing cost; Initialize A to be empty; for each edge {i, j} chosen in increasing order do u : = Find(i); v : = Find(j); if not(u = v) then add {i, j} to A; Union(u, v); 109
Kruskal code void Graph: : kruskal(){ int edges. Accepted = 0; Disj. Set s(NUM_VERTICES); |E| heap ops while (edges. Accepted < NUM_VERTICES – 1){ e = smallest weight edge not deleted yet; // edge e = (u, v) uset = s. find(u); vset = s. find(v); if (uset != vset){ 2|E| finds edges. Accepted++; s. union. Sets(uset, vset); } } } |V| unions 110
Find MST using Kruskal’s 2 A 4 D 9 7 • • 1 C 2 2 B 3 F 2 10 4 8 H 1 G Total Cost: E Now find the MST using Prim’s method. Under what conditions will these methods give the same result? 111














































































































