1 Joe Meehean.  Vertices (nodes) connected by edges (pointers)  Multiple incoming edges are OK  Cycles are OK 2.

Presentation on theme: "1 Joe Meehean.  Vertices (nodes) connected by edges (pointers)  Multiple incoming edges are OK  Cycles are OK 2."— Presentation transcript:

1 Joe Meehean

 Vertices (nodes) connected by edges (pointers)  Multiple incoming edges are OK  Cycles are OK 2

 Generalization of trees both have nodes and edges  Trees root has no incoming edges other nodes have exactly one  Graphs no restriction on incoming edges may not contain an obvious starting node 3

 Directed AKA (digraph)  Undirected We will manly consider directed graphs in class 4

 Can have labels (data) in vertices (names) on edges (weights or cost)  Ex: Airline Routes Newark Charlotte Charlottesville Dulles 1.5hrs 2hrs 1.5hrs1.25hrs 1hr 5

 Predecessor / Successor two ends of a directed edge Dulles Newark PredecessorSuccessor Adjacent ◦ vertex A is adjacent to vertex B if there is an edge between A and B (A,B) 6

 Path sequence of vertices connected by edges E.g., Charlottesville=> Dulles=> Charlotte acyclic path  no vertex is repeated  Charlottesville=> Dulles=> Charlotte cyclic path  some vertex is repeated  Newark=>Dulles=>Charlotte=>Newark  DAG: Directed Acyclic Graph directed graph with no cycles 7

 Connected undirected graph is connected if there is a path from every vertex to every other vertex  Strongly connected directed graph that is connected  Complete graph edge between every pair of vertices 8

 One Graph class for the “whole thing”  Stores vertices  some graphs have a special root vertex (simple ptr)  others must keep all vertices  array, list, set, or map  Stores counts # of vertices # of edges 9

 Adjacency matrix vertices are represented by integer 2d array A if edge between v & u, A[v][u] = true weighted graphs, A[v][u] = weight expensive in space: vertices 2 appropriate for dense graphs  nearly every vertex has an edge to nearly every other vertex most graphs are not dense 10

 Adjacency lists  Option 1: Map store a map of vertices to adjacent lists  Option 2: List in vertex class Vertex class stores data/label adjacent vertices (successors in list or set) predecessors (optional) 11

template class Vertex { //fields private: K data_; list *> successors_; friend Graph ; } 12

template class Graph { //fields private: // could use a list too set *> vertices_; int numEdges_; //constructor public Graph(){ numEdges = 0; } 13

 addVertice given vertex or data  addEdge given between vertices m & n  getVertices return list of all vertices  getSuccessors given node n  hasEdge given vertices m and n 14

// Optionally template class Edge{ private: Vertex * successor_; L label_; public: // constructor Edge(Vertex * vertex, L label){ successor_ = vertex; label_ = label; } friend class Vertex; } 15

Graph vertices: data:Charlotte succs: Vertex data: Dulles succs: Vertex data: Cville succs: Vertex 16

 Representing real world problems  Vertices represent things  Edges represent relationships between things 17

 Interdependent tasks Vertices = tasks Edge = “Must do before” CS courses w/ prereqs 141 142 271 360 380 241 242 18

 State Transition Diagrams Flashing Yellow Flashing Yellow Red Yellow Green Flashing Red 19

 Control Flow Graphs Program flow chart Start this k = 0 cond 1 cond2 that bool thisOrThat(){ int k = 0; while(cond1){ if(cond2){ //this }else{ //that } return stuff; } return stuff 20

 Graphs can answer questions like Can I fly non-stop from Chicago to Tampa? If not, what is the min hops? How many CS classes must I take before CS360? Can a variable be returned uninitialized? 21

22

 2 orderly ways to traverse graphs depth-first traversal or depth-first search (dfs) breadth-first traversal or breadth-first search (bfs) 23

 Can answer questions is graph connected? does graph have a cycle? is there a path from vertex j to vertex k? what vertices are reachable from vertex k?  Topological numbering acyclical graphs ordering where node’s # comes before all successors 24

 Start at a given vertex v  Follow an edge out of v (to u)  Follow an edge out of u  Getting as far away from v as possible  When dead-end, go back one vertex and try other successors 25

 Start with all vertices marked unvisited  Select a vertex v  dft(v) mark v visited foreach of v’s successors u  if u is unvisited: dft(u) 26

B B A A C C D D E E F F dft(A) dft(C) dft(D)dft(E) dft(B)dft(F) Visit order: A C D B F E Alternate order: A C F E D B 27

B B A A C C D D E E F F Draw a potential call trace and visit order from C 28

dft(A) dft(C) dft(D)dft(E) dft(B)dft(F) Visit order: C D B A F E 29 B B A A C C D D E E F F

 Visited/unvisited marker boolean in each vertex void Graph::dft(Vertex* v){ v->visited = true; list ::iterator iter; for(iter = v->successors.begin(); iter != v->successors.end(); iter++ ){ if( !(*iter)->visited ){ dft(*iter); } 30

 1 recursive call with each vertex reachable from v  Each call goes through successor list  Time proportional to # vertices reachable from v # of outgoing edges from those vertices  Worst case all vertices reachable from all vertices O(V + E) V is vertices in graph E is edges in graph 31

 Idea visit all nodes 1 step from v visit all nodes 2 steps from v …  Similar to level-order traversal of trees  Mark vertices to avoid visiting twice  Use BFT to… find vertices reachable from some start vertex find shortest # of hops from a vertex to another 32

void bft(Vertex* v){ queue vertexQ; v->visted = true; vertexQ.push(v); while( !vertexQ.empty() ){ Vertex* curr = vertexQ.front(); vertexQ.pop(); list ::iterator iter; for(iter = curr->succ.begin(); iter != curr->succ.end(); iter++){ if( !(*iter)->visited ){ (*iter)->visited = true; vertexQ.push(*iter); }}}} 33

 Every vertex enqueued/dequeued once  When a vertex is dequeued all successors are considered  Time proportional to… # of vertices reachable from 1 st vertex # of outgoing edges from those vertices assuming Q and iterator operators are O(1)  Worst-case time: O(V + E) 34

 Write 2 dft and 2 bft orders starting at A B B A A C C D D E E F F G G 35

B B A A C C D D E E F F G G DFS: A B F G D E A B F E D G A D F G E B A D F E G B BFS: A B D F G E A D B F G E A D B F E G A B D F E G 36  Write 2 dft and 2 bft orders starting at A

 Path detection is there a path from vertex j to vertex k? can I fly from Lynchburg to Barcelona? is 242 a prereq for 370? 1. Start with all vertices “unvisited” 2. dft(j) 3. There is a path from j to k if k is marked visited 37

 There is a path from j to k, if there is a path from any of j’s reachable vertices to k  bool isPath(Vertex* start, Vertex* end)  Base case start == end, return true  Recursive case if there is a path from any of start’s univisted successors to end, then return true else return false 38

39

 Graphs are a generalization of trees  2 ways to traverse depth-first search (DFS) breadth-first search (BFS) 40

 Find shortest path between 2 vertices  Shortest # of hops # of edges traversed  Shortest in cost for weighted graphs 41 B B A A C C D D E E F F 7 15 6 14 9 10 11 2

 Goal shortest # of hops from 1 vertex to all vertices  Input graph and starting node  Output graph with each node marked with distance unreachable marked infinity easy to calculate actual path 42

 Use BFS find all vertices within distance 1, 2, 3, ….  Additional book keeping in Vertex boolean visited  found shortest path yet  initially false int/float distance  # of hops in shortest path  initially ∞ Vertex* path  vertex before this one on shortest path  initially NULL 43

1. Set distance of starting vertex to 0 2. Set current vertex to starting vertex 3. Mark it visited 4. For each of current’s ∞ distance successors a) set their distance to 1 + current’s distance b) set their path to current vertex c) add successor to queue 5. Take vertex off of queue, set to current 6. Go to 3, until queue is empty 44

45 B B A A C C D D E E F F ShortestHops(A) vertexvisiteddistancepath AF∞NULL BF∞ CF∞ DF∞ EF∞ FF∞ Queue

46 B B A A C C D D E E F F ShortestHops(A) vertexvisiteddistancepath AT0NULL BF1A CF1A DF∞ EF∞ FF1A B C F Queue

47 B B A A C C D D E E F F ShortestHops(A) vertexvisiteddistancepath AT0NULL BT1A CF1A DF2B EF∞ FF1A B C F D Queue

48 B B A A C C D D E E F F ShortestHops(A) vertexvisiteddistancepath AT0NULL BT1A CT1A DF2B EF∞ FF1A B C F D Queue

49 B B A A C C D D E E F F ShortestHops(A) vertexvisiteddistancepath AT0NULL BT1A CT1A DF2B EF2F FT1A B C F D E Queue

50 B B A A C C D D E E F F ShortestHops(A) vertexvisiteddistancepath AT0NULL BT1A CT1A DT2B EF2F FT1A B C F D E Queue

51 B B A A C C D D E E F F ShortestHops(A) vertexvisiteddistancepath AT0NULL BT1A CT1A DT2B ET2F FT1A B C F D E Queue

 Path can be constructed using path variable from vertices void constructPath(list & path, Vertex* start, Vertex* end){ if( start != end ){ path.push_front(end); constructPath(path, start, end->path); } 52

 Complexity update each vertex once (twice really) check every edge once for infinity O(E + V) 53

 BFS algorithm only finds shortest # of hops between 2 vertices  What if the edges are weighted? I can get from Roanoke to Boston in 2 hops by flying to Chicago But I can get there quicker using 3 hops  Roanoke => Dulles => JFK => Boston (Logan) 54

 Goal shortest path for a weighted graph  Input graph and starting node  Output graph with each node marked with distance unreachable marked infinity  Restrictions no negative weights 55

1. Assign tentative distances 2. Move node with smallest distance to completed set 3. Update the distance of its successors 4. Go to Step 2 56

 Updated book keeping distance is now shortest path using only visited vertices path is last vertex to update distance 57

Graph::dijkstra(Vertex* v){ set all verticees unvisted and distance to infinity v.distance = 0; add all vertices to uncompleted prioQ while( uncompleted has nodes ){ remove vertex u with smallest distance set u visited for all u’s unvisited successors s{ new_dist = u.distance + edge(u,s) if( s.distance > new_dist ){ s.distance = new_dist; s.path = u; }}}} 58

B B A A C C D D E E F F 7 15 6 9 14 9 10 11 2 59 vertexvisiteddistancepath AF∞NULL BF∞ CF∞ DF∞ EF∞ FF∞ Priority Queue Uncompleted

B B A A C C D D E E F F 7 15 6 9 14 9 10 11 2 60 vertexvisiteddistancepath AT0NULL BF∞ CF∞ DF∞ EF∞ FF∞ Priority Queue Uncompleted A B C D E F

B B A A C C D D E E F F 7 15 6 9 14 9 10 11 2 61 vertexvisiteddistancepath AT0NULL BF7A CF9A DF∞ EF∞ FF14A Priority Queue Uncompleted A B C F D E

B B A A C C D D E E F F 7 15 6 9 14 9 10 11 2 62 vertexvisiteddistancepath AT0NULL BT7A CF9A DF22B EF∞NULL FF14A Priority Queue Uncompleted A B C F D E

B B A A C C D D E E F F 7 15 6 9 14 9 10 11 2 63 vertexvisiteddistancepath AT0NULL BT7A CT9A DF22 20B C EF∞NULL FF14 11A CA C Priority Queue Uncompleted A B C F D E

B B A A C C D D E E F F 7 15 6 9 14 9 10 11 2 64 vertexvisiteddistancepath AT0NULL BT7A CT9A DF22 20B C EF20F FT14 11A C Priority Queue Uncompleted A B C F D E

B B A A C C D D E E F F 7 15 6 9 14 9 10 11 2 65 vertexvisiteddistancepath AT0NULL BT7A CT9A DT22 20B C EF20F FT14 11A C Priority Queue Uncompleted A B C F D E

B B A A C C D D E E F F 7 15 6 9 14 9 10 11 2 66 vertexvisiteddistancepath AT0NULL BT7A CT9A DT22 20B C ET20F FT14 11A C Priority Queue Uncompleted A B C F D E

 Complexity find min distance vertex  priority Q remove max = O(logV) find min distance vertex for all vertices  O(VlogV) update vertex distance  priority Q update entry = O(logV) update vertex distance for each edge  O(ElogV) O(ElogV + VlogV) = O(ElogV) 67

 What kind of algorithm is Dijkstra’s shortest path?  Why does it work? 68

69

 Ordering of vertices in a directed graph if there is a path from v to u v has a smaller topological # than u u appears after v in the ordering  Not possible if the graph has cycles if v and u are in a cycle v can be both before and after u 70

 Algorithm overview find a vertex with an in-degree of 0 it can have the smallest topological # remove it and its edges from the graph repeat  Additional bookkeeping add inDegree variable to Vertex add topological # variable (topnum) to Vertex 71

 Algorithm in detail 72 void Graph::topologicalSort(){ compute in-degree for all vertices add all vertices to inprogress list globalTopNum = 0; while inprogress is not empty{ find vertex v with in-degree 0 in list remove v from inprogress v.topnum = globalTopNum++; decrement indegree of all of v’s sucessors }

73 vertexin-degreetopnum A3NULL B0 C2 D2 E1 D D A A C C E E B B InProgress A B C D E GlobalTopNum = 0

74 vertexin-degreetopnum A3 2NULL B00 C2 1NULL D2 E1 0NULL D D A A C C E E B B InProgress A B C D E GlobalTopNum = 1

75 vertexin-degreetopnum A3 2NULL B00 C2 1 0NULL D2 1NULL E1 01 D D A A C C E E B B InProgress A B C D E GlobalTopNum = 2

76 vertexin-degreetopnum A3 2 1NULL B00 C2 1 02 D NULL E1 01 D D A A C C E E B B InProgress A B C D E GlobalTopNum = 3

77 vertexin-degreetopnum A3 2 1 0NULL B00 C2 1 02 D 3 E1 01 D D A A C C E E B B InProgress A B C D E GlobalTopNum = 4

78 vertexin-degreetopnum A3 2 1 04 B00 C2 1 02 D 3 E1 01 D D A A C C E E B B InProgress A B C D E GlobalTopNum = 5

 Complexity scan in-progress for 0 in-degree vertex: O(V) for each vertex: O(V 2 ) update in-degree for every edge: O(E) O(E) + O(V 2 ) = O(V 2 )  at most O(E) can be O(V 2 )  if there is an edge between each vertex 79

 Can we do better? create queue for 0 in-degree vertices compute in-degree for all vertices  put any 0 in-degree vertex in the queue remove vertex v from queue set its topological number decrement in-degree of all successors  adding any 0 in-degree vertices in the queue repeat while queue is not empty 80

 Improved complexity set all vertices in-degree: O(V) en/dequeue: O(V) + O(V) update vertices in-degree: O(E) O(V) + O(V) + O(V) + O(E) = O(V+E) linear => much improved 81

 Cycles in graphs can be undesirable e.g., course perquisites should never have a cycle e.g., course A is a prereq for B, which is prereq for C, but course C is a prereq for course A  Need a way to detect cycles in a graphs (directed graphs in particular) 82

 Checking for cycles with DFT?  Ex 1 starting at A when we get to C A is a visited successor B B A A C C dfs(A) dfs(B) dfs(C) 83

 Checking for cycles with DFT?  Ex 2 starting at A when we get to C B is a visited successor but there is no cycle here B B A A C C dfs(A) dfs(B)dfs(C) 84

 DFT makes a tree 85 D D A A C C F F E E B B G G H H B B D D A A C C E E

 May need to start at several vertices  makes a forest 86 D D A A C C F F E E B B G G H H B B D D A A C C E E G G H H F F

 Can add edges not taken during traversal edges where node was already marked visited 87 D D A A C C F F E E B B G G H H B B D D A A C C E E G G H H F F

 Forward edges to descendants 88 B B D D A A C C E E G G H H F F

 Back edges to ancestors 89 B B D D A A C C E E G G H H F F

 Cross edges to another tree edges to others e.g, siblings, nephews 90 B B D D A A C C E E G G H H F F

 Directed graph is acyclic iff it has no back edges  Need to distinguish between edges during traversal to detect cycles 91 B B D D A A C C E E G G H H F F

 Additional bookkeeping convert visited from boolean to 3-value unvisited: not traversed visited: vertex’s descendant are all visited inprogress: vertex’s descendants are still being traversed  If a vertex’s successor is in inprogress, this vertex must be a descendant of it’s own successor there must be a cycle 92

93 mark v “in progress” for each successor u{ if u is “in progress” return true else if u is “unvisited” and hasCycle(u) return true } mark v “visited” return false

94

 Lecture will focus on undirected graphs  Spanning tree a tree formed from edges that connect all vertices in a graph can only exist if graph is connected  Minimum spanning tree spanning tree with the lowest cost (in edge weights) 95

96 D D A A C C E E B B 5 15 3 4 6 1 7 1 D D A A C C E E B B 3 4 1 1

 For any spanning tree adding another edge creates a cycle removing any edge from the cycle recreates a spanning tree if added edge has smaller weight than the removed edge the tree cost is lowered 97

 When creating tree if edges are added by lowest cost with no cycles resulting tree is minimum spanning tree greedy algorithm 98

 Series of greedy stages  Select a vertex as the root of the tree add an edge (and vertex) to the tree at every stage  Eventually all vertices in tree 99

 Algorithm divide vertices into 2 sets  those in tree and those that aren’t start by adding single vertex to tree  becomes the root add edge with lowest weight that connects vertex in tree with vertex not in tree repeat adding edges until all vertices in tree 100

 Nearly identical to Dijkstra’s algoritm except distance is to tree not root  For each vertex v update its successor u’s distance min of u’s current distance and the cost of the edge from u to v u.distance = min(u.distance, cost(u,v)) 101

102 vertexknowndistancepath AF∞NULL BF∞ CF∞ DF∞ EF∞ FF∞ A B C D E F B B A A C C D D E E F F 7 15 6 14 9 10 11 2 PriorityQ Uncompleted 9

103 vertexknowndistancepath AT0NULL BF7A CF9A DF∞ EF∞ FF14A A B C F D E B B A A C C D D E E F F 7 15 6 14 9 10 11 2 PriorityQ Uncompleted 9 A A

104 vertexknowndistancepath AT0NULL BT7A CF9A DF15B EF∞NULL FF14A A B C F D E B B A A C C D D E E F F 7 15 6 14 9 10 11 2 PriorityQ Uncompleted 9 B B A A 7

105 vertexknowndistancepath AT0NULL BT7A CT9A DF11C EF∞NULL FF2C A B C F D E B B A A C C D D E E F F 7 15 6 14 9 10 11 2 PriorityQ Uncompleted 9 B B A A C C 7 9

106 vertexknowndistancepath AT0NULL BT7A CT9A DF11C EF9F FT2C A B C F E D B B A A C C D D E E F F 7 15 6 14 9 10 11 2 PriorityQ Uncompleted 9 B B A A C C F F 7 9 2

107 vertexknowndistancepath AT0NULL BT7A CT9A DF6C ET9F FT2C A B C F E D B B A A C C D D E E F F 7 15 6 14 9 10 11 2 PriorityQ Uncompleted 9 B B A A C C E E F F 7 9 2 9

108 vertexknowndistancepath AT0NULL BT7A CT9A DT6E ET9F FT2C A B C F E D B B A A C C D D E E F F 7 15 6 14 9 10 11 2 PriorityQ Uncompleted 9 B B A A C C D D E E F F 7 9 2 9 6

 Complexity identical to Dijkstra’s O(V 2 ) without a priority queue O(ElogV) with a priority queue 109

 Also greedy  Add edges in order of smallest weight ensuring they do not create a cycle  Start with a forest of 1 node trees one for each vertex  Add edges until there is only 1 tree adding edges merges two trees only add edges that do not introduce a cycle 110

 How to tell which edges are safe to add? adding an edge between 2 vertices in the same tree will make a cycle only add edges between vertices in different trees adding an edge puts both vertices in the same tree 111

112 vertextree(root) AA BB CC DD EE FF B B A A C C D D E E F F 7 15 6 14 9 10 11 2 9 edgeweightaction CFCF2 DEDE6 ABAB7 ACAC9 EFEF9 BCBC10 CDCD11 AFAF14 BDBD15 B B A A C C D D E E F F

113 vertextree(root) AA BB CC DD EE FC B B A A C C D D E E F F 7 15 6 14 9 10 11 2 9 edgeweightaction CFCF2Accept DEDE6 ABAB7 ACAC9 EFEF9 BCBC10 CDCD11 AFAF14 BDBD15 B B A A C C D D E E F F 2

114 vertextree(root) AA BB CC DD ED FC B B A A C C D D E E F F 7 15 6 14 9 10 11 2 9 edgeweightaction CFCF2Accept DEDE6 ABAB7 ACAC9 EFEF9 BCBC10 CDCD11 AFAF14 BDBD15 B B A A C C D D E E F F 2 6

115 vertextree(root) AA BA CC DD ED FC B B A A C C D D E E F F 7 15 6 14 9 10 11 2 9 edgeweightaction CFCF2Accept DEDE6 ABAB7 ACAC9 EFEF9 BCBC10 CDCD11 AFAF14 BDBD15 B B A A C C D D E E F F 2 6 7

116 vertextree(root) AA BA CA DD ED FA B B A A C C D D E E F F 7 15 6 14 9 10 11 2 9 edgeweightaction CFCF2Accept DEDE6 ABAB7 ACAC9 EFEF9 BCBC10 CDCD11 AFAF14 BDBD15 B B A A C C D D E E F F 2 6 7 9

117 vertextree(root) AA BA CA DA EA FA B B A A C C D D E E F F 7 15 6 14 9 10 11 2 9 edgeweightaction CFCF2Accept DEDE6 ABAB7 ACAC9 EFEF9 BCBC10 CDCD11 AFAF14 BDBD15 B B A A C C D D E E F F 2 6 7 9 9

118 vertextree(root) AA BA CA DA EA FA B B A A C C D D E E F F 7 15 6 14 9 10 11 2 9 edgeweightaction CFCF2Accept DEDE6 ABAB7 ACAC9 EFEF9 BCBC10Reject CDCD11Reject AFAF14Reject BDBD15Reject B B A A C C D D E E F F 7 6 9 2 9

 Complexity uses the union-find algorithm  can check set membership and combine sets in O(logV)  see Weiss Ch 8 need to check for every edge  O(E) O(ElogV) 119

120

 Graph Coloring undirected graphs related vertices connected by an edge goal: assign each vertex a color no vertex should have the same color as its assigned vertices  Applications coloring maps register allocation 121

 Terminology “colors” may be anything  can be represented as #’s k-coloring: coloring a graph using k colors chromatic #: smallest # of colors needed to color a graph 122

 Problem: color an arbitrary graph with as few colors as possible  Can always color a graph with V colors  Can we do better? 123

 Option 1: Brute force  Try coloring graph with all k values k = 1, 2, …, V  Check every possible color assignment try all colors for each vertex total possible combinations: k v V possible chromatic #’s  Complexity: V*V V = V V+1 = O(V V ) 124

 Option 1: Brute force  E.g., World map ~196 countries operations = 196 196 = 1.9 * 10 449 on 3GHz machine would take 2*10 432 years 1.5 * 10 422 times the age of the universe  Can we do better? 125

 Option 2: Greedy approach  Order vertices by their degree # of edges, max heap  Order the colors arbitrarily blue = 1, red = 2, …  For each vertex assign it the smallest color that does not conflict with its neighbors 126

127 F F E E B B A A C C D D

128 F F E E B B A A C C D D 1234512345 Priority Queue Uncolored F C A B E D

129 F F E E B B A A C C D D 1234512345 Priority Queue Uncolored F C A B E D

130 F F E E B B A A C C D D 1234512345 Priority Queue Uncolored F C A B E D

131 F F E E B B A A C C D D 1234512345 Priority Queue Uncolored F C A B E D

132 F F E E B B A A C C D D 1234512345 Priority Queue Uncolored F C A B E D

133 F F E E B B A A C C D D 1234512345 Priority Queue Uncolored F C A B E D

134 F F E E B B A A C C D D 1234512345 Priority Queue Uncolored F C A B E D

 If graph’s max degree is d largest degree for any vertex is d  Graph will be colored with at most d+1 colors  This may be arbitrarily larger than the graph’s chromatic # 135

136 1 1 5 5 2 2 6 6 3 3 7 7 4 4 8 8 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8

 Sort vertices by degree use a max heap insert: log V performed V times = VlogV 137

 Assign a color to a vertex removeMax = log V check neighbors colors = d for each color = d + 1 = d * d+1 = O(d 2 ) done for each vertex: d 2 V log V  Total Complexity VlogV + d 2 V log V = O(d 2 V log V) 138

 E.g., World Map 196 countries China & Russia have most boundaries: 14 O(d 2 V log V) = 14 2 * 196 * log *196 ≈ 290,000 Computes in less than 1s on 3GHz processor 139

 Graph set of vertices and set of edges  Two types of graphs directed and undirected  Low level operations add node, edge remove node, edge 140

 High level operations DFS: reachability, cycle detection, topological numbering BFS: reachability, shortest hops Dijkstra’s shortest path for weighted graphs topological sort cycle detection minimum spanning trees graph coloring many, many other operations 141

142

143

B B A A C C D D E E F F G G  Draw call trace to find order of all nodes  Assume successor lists are in alphabetical order 144

topNum(C,3) topNum(A,7) topNum(B,7) topNum(D,5) topNum(F,3) topNum(E,7) topNum(G,2) 6 3 5 4 0 1 2 145

 Biconnected graph connected must remove at least 2 vertices to disconnect graph  E.g., transit system biconnected transit system could have a single closed station and passengers could still get to all other destinations 146

147 D D E E B B A A C C D D E E B B A A C C F F Biconnected Not Biconnected

 Articulated points vertices found in non-biconnected graphs if removed graph becomes disconnected 148 D D E E B B A A C C F F

 Extra vertex bookkeeping number low parent (in DFS tree)  Assign vertices numbers sequentially number vertices as they are visited use a preorder DFS first vertex is assigned 1 last vertex visited is assigned N 149

 Assign each vertex a low#  Lowest vertex number reachable by following 0 or more tree edges and then possible a back edge 150

151 F F E E B B A A C C A,1/ 1 C, 2/1 D, 3/3 F, 4/1 D D B, 5/4 E, 6/4

 Vertex v.low is 1. v.num  take no edges 2. min (u.num) for a v’s backedges (v,u)  take immediate back edge 3. min (w.low) for all v’s tree edges (v,w)  take some tree edges and possible a back edge 152

 Root is articulation point if it has more than 1 child if it has 2 children, removing root will disconnect trees  Other vertices v are articulation point iff v has a child w where w.low ≥ v.number w cannot get to v’s ancestors, except possibly through v removing v disconnects w from v’s ancestors 153

 Assign vertex numbers DFS: O(E + V)  Assign low numbers DFS: O(E + V)  Compare numbers to low numbers DFS: O(E + V)  Complexity O(E+V) + O(E+V) + O(E+V) = O(E+V) 154

155

156 G G F F D D E E B B A A C C

157 list Graph::findArtPts(){ int number = 1; assignNum(vertices[0], &number); assignLow(vertices[0]); list artPts; findArtPts(vertices[0], &artPts); return artPts; }

158 void Graph::assignNum( Vertex* v, int* number){ // You fill in }

159 void Graph::assignNum( Vertex* v, int* number){ v->number = (*number)++; v->visited = true; foreach(successor w){ if( !w->visited ){ w->parent = v; assignNum(w,number); }

160 void Graph::assignLow( Vertex* v){ // you fill in }

161 void Graph::assignLow( Vertex* v){ v->low = v->number; // rule 1 foreach(successor w){ if( w->num > v->num) // forward edge assignLow(w); // rule 3 v->low = min(v->low, w->low); } else if( v->parent != w ){ //back edge // rule 2 v->low = min(v->low, w->number); }

162 void Graph::findArtPts( Vertex* v, list * artPts){ // You fill in }

163 void Graph::findArtPts( Vertex* v, list * artPts){ foreach(successor w){ if( w->low >= v->num ){ artPts.push_back(v); }

 Graph represents a network e.g. data network, plumbing, street plan  Edge labels represent flow capacities larger is better  For each vertex total flow coming in = total flow going out distributes flow however it wants as long as edge capacities aren’t violated 164

 What is the max flow (capacity) between 2 vertices? source: start of flow (s) sink: end of flow (t) 165

166 D D A A C C T T B B 2 S S 3 1 4 2 3 2 3 D D A A C C T T B B 2 S S 3 0 1 2 2 2 3 Max Flow: 5

 Create a 2 nd graph, G f flow graph store in-progress state of solution shows total flow along edges  Create a 3 rd graph, G r residual graph more in-progress state shows remaining capacity for each edge remove saturated (0 capacity) edges 167

 At each stage find path in G r from s to t called an augmentation path minimum edge determines additional flow add this flow to solution update G r and G f along this path  Repeat until no path from s to t exists in G r 168

169 D D A A C C T T B B 2 S S 3 1 4 2 3 2 3 D D A A C C T T B B 2 S S 3 0 1 2 2 2 3

170 D D A A C C T T B B 2 S S 3 1 4 2 3 2 3 D D A A C C T T B B 0 S S 0 0 0 0 0 0 0 D D A A C C T T B B 2 S S 3 1 4 2 3 2 3 G GfGf GrGr

171 D D A A C C T T B B 2 S S 3 1 4 2 3 2 3 D D A A C C T T B B 2 S S 0 0 0 2 0 0 2 D D A A C C T T B B S S 3 1 4 3 2 1 G GfGf GrGr Augmentation Path: S, B, D, T (2 units)

172 D D A A C C T T B B 2 S S 3 1 4 2 3 2 3 D D A A C C T T B B 2 S S 2 0 0 2 2 2 2 D D A A C C T T B B S S 1 1 4 1 1 G GfGf GrGr Augmentation Path: S, A, C, T (2 units)

173 D D A A C C T T B B 2 S S 3 1 4 2 3 2 3 D D A A C C T T B B 2 S S 3 0 1 2 2 2 3 D D A A C C T T B B S S 1 3 1 G GfGf GrGr Augmentation Path: S, A, D, T (1 unit)

174 D D A A C C T T B B 2 S S 3 1 4 2 3 2 3 D D A A C C T T B B 2 S S 3 0 1 2 2 2 3 D D A A C C T T B B S S 1 3 1 G GfGf GrGr No path from S to T in G r

 Flaw order of augmentation paths matters greedy is not the right approach 175

176 D D A A C C T T B B 2 S S 3 1 4 2 3 2 3 D D A A C C T T B B 0 S S 0 0 0 0 0 0 0 D D A A C C T T B B 2 S S 3 1 4 2 3 2 3 G GfGf GrGr

177 D D A A C C T T B B 2 S S 3 1 4 2 3 2 3 D D A A C C T T B B 0 S S 3 0 3 0 0 0 3 D D A A C C T T B B 2 S S 1 1 2 3 2 G GfGf GrGr Augmentation Path: S, A, D, T (3 units)

178 D D A A C C T T B B 2 S S 3 1 4 2 3 2 3 D D A A C C T T B B 0 S S 3 0 3 0 0 0 3 D D A A C C T T B B 2 S S 1 1 2 3 2 G GfGf GrGr No path from S to T

 Need to be able to undo previous choice  For each edge (v,w) with flow v,w in G f add edge (w,v) with flow v,w in G r  Allows algorithm to send flow back later undo all/part of previous augmentation path 179

180 D D A A C C T T B B 2 S S 3 1 4 2 3 2 3 D D A A C C T T B B 0 S S 0 0 0 0 0 0 0 D D A A C C T T B B 2 S S 3 1 4 2 3 2 3 G GfGf GrGr

181 D D A A C C T T B B 2 S S 3 1 4 2 3 2 3 D D A A C C T T B B 0 S S 3 0 3 0 0 0 3 D D A A C C T T B B 2 S S 3 1 1 2 3 2 3 G GfGf GrGr Augmentation Path: S, A, D, T (3 units) 3

182 D D A A C C T T B B 2 S S 3 1 4 2 3 2 3 D D A A C C T T B B 2 S S 3 0 1 2 2 2 3 D D A A C C T T B B 2 S S 3 1 3 2 1 2 3 G GfGf GrGr Augmentation Path: S, B, D, A, C, T (2 units) 1 2

183 D D A A C C T T B B 2 S S 3 1 4 2 3 2 3 D D A A C C T T B B 2 S S 3 0 1 2 2 2 3 D D A A C C T T B B 2 S S 3 1 3 2 1 2 3 G GfGf GrGr No path from S to T 1 2

 Always choose augmentation path with largest increase in flow improves complexity/performance easy to do using modified Dijkstra’s SP 184

185

186 D D A A C C T T B B S S 2 E E 4 7 5 4 7 5 10 3

Download ppt "1 Joe Meehean.  Vertices (nodes) connected by edges (pointers)  Multiple incoming edges are OK  Cycles are OK 2."

Similar presentations