Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 10. Graphs.

Slides:



Advertisements
Similar presentations
Lecture 15. Graph Algorithms
Advertisements

Graphs Chapter 20 Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013.
Graphs Graphs are the most general data structures we will study in this course. A graph is a more general version of connected nodes than the tree. Both.
Graph.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 21: Graphs.
1 Spanning Trees Lecture 20 CS2110 – Spring
Prof. Amr Goneid, AUC1 Analysis & Design of Algorithms (CSCE 321) Prof. Amr Goneid Department of Computer Science, AUC Part R5. Graphs.
Graph & BFS.
CS 311 Graph Algorithms. Definitions A Graph G = (V, E) where V is a set of vertices and E is a set of edges, An edge is a pair (u,v) where u,v  V. If.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Graphs.
CS Data Structures Chapter 6 Graphs.
Graphs Chapter 20 Data Structures and Problem Solving with C++: Walls and Mirrors, Frank Carrano, © 2012.
Review of Graphs A graph is composed of edges E and vertices V that link the nodes together. A graph G is often denoted G=(V,E) where V is the set of vertices.
C o n f i d e n t i a l HOME NEXT Subject Name: Data Structure Using C Unit Title: Graphs.
GRAPHS Education is what remains after one has forgotten what one has learned in school. Albert Einstein Albert Einstein Smitha N Pai.
Data Structures Using C++ 2E
IS 2610: Data Structures Graph April 5, 2004.
Graphs CS 400/600 – Data Structures. Graphs2 Graphs  Used to represent all kinds of problems Networks and routing State diagrams Flow and capacity.
Theory of Computing Lecture 10 MAS 714 Hartmut Klauck.
Graphs. Motivating Problem Konigsberg bridge problem (1736): Konigsberg bridge problem (1736): C A B D ab c d e f g Starting in one land area, is it possible.
1 Abstract Data Type We have discussed: List Tree Today we will talk about Graph.
Chapter 9 – Graphs A graph G=(V,E) – vertices and edges
CS 3343: Analysis of Algorithms Lecture 21: Introduction to Graphs.
Graph Theoretic Concepts. What is a graph? A set of vertices (or nodes) linked by edges Mathematically, we often write G = (V,E)  V: set of vertices,
Chapter 2 Graph Algorithms.
Chapter 14 Graphs. © 2004 Pearson Addison-Wesley. All rights reserved Terminology G = {V, E} A graph G consists of two sets –A set V of vertices,
CS200 Algorithms and Data StructuresColorado State University Part 10. Graphs CS 200 Algorithms and Data Structures 1.
Representing and Using Graphs
Minimum Spanning Trees CSE 2320 – Algorithms and Data Structures Vassilis Athitsos University of Texas at Arlington 1.
© 2015 JW Ryder CSCI 203 Data Structures1. © 2015 JW Ryder CSCI 203 Data Structures2.
Prof. Amr Goneid, AUC1 Analysis & Design of Algorithms (CSCE 321) Prof. Amr Goneid Department of Computer Science, AUC Part 12. Graph Algorithms.
Prims’ spanning tree algorithm Given: connected graph (V, E) (sets of vertices and edges) V1= {an arbitrary node of V}; E1= {}; //inv: (V1, E1) is a tree,
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Graphs.
Graphs. Definitions A graph is two sets. A graph is two sets. –A set of nodes or vertices V –A set of edges E Edges connect nodes. Edges connect nodes.
Data Structures & Algorithms Graphs
10 Copyright © William C. Cheng Data Structures - CSCI 102 Graph Terminology A graph consists of a set of Vertices and a set of Edges C A B D a c b d e.
CISC 235: Topic 9 Introduction to Graphs. CISC 235 Topic 92 Outline Graph Definition Terminology Representations Traversals.
Graphs A ‘Graph’ is a diagram that shows how things are connected together. It makes no attempt to draw actual paths or routes and scale is generally inconsequential.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 13: Graphs Data Abstraction & Problem Solving with C++
Graphs Graphs are collections of vertices and edges. Vertices are simple objects with associated names and other properties. Edges are connections between.
1 Directed Graphs Chapter 8. 2 Objectives You will be able to: Say what a directed graph is. Describe two ways to represent a directed graph: Adjacency.
© 2006 Pearson Addison-Wesley. All rights reserved 14 A-1 Chapter 14 Graphs.
Chapter 6 Graphs. 2 Outline Definitions, Terminologies and Applications Graph Representation Elementary graph operations Famous Graph Problems.
Graphs and Paths : Chapter 15 Saurav Karmakar
Chapter 20: Graphs. Objectives In this chapter, you will: – Learn about graphs – Become familiar with the basic terminology of graph theory – Discover.
Graph Revisited Fei Chen CSCI2100B Data Structures Tutorial 12 1.
Chapter 05 Introduction to Graph And Search Algorithms.
Data Structures and Algorithm Analysis Graph Algorithms Lecturer: Jing Liu Homepage:
Graphs Rosen, Chapter 8. NOT ONE OF THESE! One of these!
Lecture #13. Topics 1.The Graph Abstract Data Type. 2.Graph Representations. 3.Elementary Graph Operations.
Midwestern State University Minimum Spanning Trees Definition of MST Generic MST algorithm Kruskal's algorithm Prim's algorithm 1.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 10. Graphs.
1 GRAPHS – Definitions A graph G = (V, E) consists of –a set of vertices, V, and –a set of edges, E, where each edge is a pair (v,w) s.t. v,w  V Vertices.
Lecture 20. Graphs and network models 1. Recap Binary search tree is a special binary tree which is designed to make the search of elements or keys in.
CSC317 1 At the same time: Breadth-first search tree: If node v is discovered after u then edge uv is added to the tree. We say that u is a predecessor.
1 Data Structures and Algorithms Graphs. 2 Graphs Basic Definitions Paths and Cycles Connectivity Other Properties Representation Examples of Graph Algorithms:
BCA-II Data Structure Using C Submitted By: Veenu Saini
CSCE 210 Data Structures and Algorithms
Graphs Lecture 19 CS2110 – Spring 2013.
I206: Lecture 15: Graphs Marti Hearst Spring 2012.
CS120 Graphs.
Graph Algorithm.
Spanning Trees.
Graphs Chapter 13.
Graphs Chapter 15 explain graph-based algorithms Graph definitions
Graphs.
What is a Graph? a b c d e V= {a,b,c,d,e} E= {(a,b),(a,c),(a,d),
Chapter 11 Graphs.
CSE 373: Data Structures and Algorithms
INTRODUCTION A graph G=(V,E) consists of a finite non empty set of vertices V , and a finite set of edges E which connect pairs of vertices .
Presentation transcript:

Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 10. Graphs

Prof. Amr Goneid, AUC2 Graphs

3 Graphs Basic Definitions Paths and Cycles Connectivity Other Properties Representation Examples of Graph Algorithms: Graph Traversal Shortest Paths Minimum Cost Spanning Trees

Prof. Amr Goneid, AUC4 1. Basic Definitions A graph G (V,E) can be defined as a pair (V,E), where V is a set of vertices, and E is a set of edges between the vertices E = {(u,v) | u, v  V}. e.g. V = {A,B,C,D,E,F,G} E = {( A,B),(A,F),(B,C),(C,G),(D,E),(D,G),(E,F),(F,G)} If no weights are associated with the edges, an edge is either present(“1”) or absent (“0”). A F GB E DC

Prof. Amr Goneid, AUC5 Basic Definitions A graph is like a road map. Cities are vertices. Roads from city to city are edges. You could consider junctions to be vertices, too. If you don't want to count them as vertices, a road may connect more than two cities. So strictly speaking you have hyperedges in a hypergraph. If you want to allow more than one road between each pair of cities, you have a multigraph, instead.

Prof. Amr Goneid, AUC6 Basic Definitions Adjacency: If vertices u,v have an edge e = (u,v) | u, v  V then u and v are adjacent. A weighted graph has a weight associated with each edge. Undirected Graph is a graph in which the adjacency is symmetric, i.e., e = (u,v) = (v,u) A Sub-Graph: has a subset of the vertices and the edges A F GB E DC

Prof. Amr Goneid, AUC7 Basic Definitions Directed Graph: is a graph in which adjacency is not symmetric, i.e., (u,v)  (v,u) Such graphs are also called “Digraphs” Directed Weighted Graph: A directed graph with a weight for each edge. Also called a network. A F GB E DC

Prof. Amr Goneid, AUC8 2. Paths & Cycles Path: A list of vertices of a graph where each vertex has an edge from it to the next vertex. Simple Path: A path that repeats no vertex. Cycle: A path that starts and ends at the same vertex and includes other vertices at most once. A F GB E DC A F GB E DC

Prof. Amr Goneid, AUC9 Directed Acyclic Graph (DAG) Directed Acyclic Graph (DAG): A directed graph with no path that starts and ends at the same vertex A F GB E DC

Prof. Amr Goneid, AUC10 Hamiltonian Cycle Hamiltonian Cycle: A cycle that includes all other vertices only once, e.g. {D,B,C,G,A,F,E,D} Named after Sir William Rowan Hamilton (1805 –1865) The Knight’s Tour problem is a Hamiltonian cycle problemKnight’s Tour A F GB E DC Icosian Game

Prof. Amr Goneid, AUC11 Hamiltonian Cycle Demo A Hamiltonian Cycle is a cycle that visits each node exactly once. Here we show a Hamiltonian cycle on a 5-dimensional hypercube. It starts by completely traversing the 4-dimensional hypercube on the left before reversing the traversal on the right subcube. Hamiltonian cycles on hypercubes provide constructions for Gray codes: orderings of all subsets of n items such that neighboring subsets differ in exactly one element. Hamilitonian cycle is an NP-complete problem, so no worst-case efficient algorithm exists to find such a cycle. In practice, we can find Hamiltonian cycles in modest-sized graphs by using backtracking with clever pruning to reduce the search space.

Prof. Amr Goneid, AUC12 Hamiltonian Cycle Demo inatorica/animations/ham.html Hamiltonian Cycle Demo

Prof. Amr Goneid, AUC13 Euler Circuit Leonhard Euler Konigsberg Bridges (1736) (not Eulerian) Euler Circuit: A cycle that includes every edge once. Used in bioinformatics to reconstruct the DNA sequence from its fragments

Prof. Amr Goneid, AUC14 Euler Circuit Demo An Euler circuit in a graph is a traversal of all the edges of the graph that visits each edge exactly once before returning home. A graph has an Euler circuit if and only if all its vertices are that of even degrees. It is amusing to watch as the Euler circuit finds a way back home to a seemingly blocked off start vertex. We are allowed (indeed required) to visit vertices multiple times in an Eulerian cycle, but not edges.

Prof. Amr Goneid, AUC15 Euler Circuit Demo atorica/animations/euler.html Euler Circuit Demo

Prof. Amr Goneid, AUC16 3. Connectivity Connected Graph: An undirected graph with a path from every vertex to every other vertex A Disconnected Graph may have several connected components Tree: A connected Acyclic graph A F GB E DC A F GB E DC

Prof. Amr Goneid, AUC17 Connected Components Demo What happens when you start with an empty graph and add random edges between vertices? As you add more and more edges, the number of connected components in the graph can be expected to drop, until finally the graph is connected. An important result from the theory of random graphs states that such graphs very quickly develop a single ``giant'' component which eventually absorbs all the vertices.

Prof. Amr Goneid, AUC18 Connected Components Demo atorica/animations/concomp.html Randomly Connected Graph Demo

Prof. Amr Goneid, AUC19 Connectivity Articulation Vertex: if removed with all of its edges will cause a connected graph to be disconnected, e.g., G and D are articulation vertices A F B E DC A F GB E DC

Prof. Amr Goneid, AUC20 Connectivity Degree Of a vertex, the number of edges connected to it. Degree Of a graph, the maximum degree of any vertex (e.g. B has degree 2, graph has degree 3). In a connected graph the sum of the degrees is twice the number of edges, i.e A F GB E DC

Prof. Amr Goneid, AUC21 Connectivity In-Degree/Out-Degree: the number of edges coming into/emerging from a vertex in a connected graph (e.g. G has in-degree 3 and out-degree 1). A F GB E DC

Prof. Amr Goneid, AUC22 Connectivity Complete Graph: There is an edge between every vertex and every other vertex. In this case, the number of edges is maximum: Notice that the minimum number of edges for a connected graph ( a tree in this case) is (V-1) A D CB

Prof. Amr Goneid, AUC23 Density (of edges) Density of a Graph: Dense Graph: Number of edges is close to E max = V(V-1)/2. So, E =  (V 2 ) and D is close to 1 Sparse Graph: Number of edges is close to E min = (V-1). So, E = O(V)

Prof. Amr Goneid, AUC24 4. Other Properties Planar Graph: A graph that can be drawn in the plain without edges crossing A D CB A D CB Non-Planar

Prof. Amr Goneid, AUC25 Other Properties Graph Coloring: To assign color (or any distinctive mark) to vertices such that no two adjacent vertices have the same color. The minimum number of colors needed is called the Chromatic Order of the graph  (G). For a complete graph,  (G) = V

Prof. Amr Goneid, AUC26 Other Properties An Application: Find the number of exam slots for 5 courses. If a single student attends two courses, an edge exists between them. EE Math CS PhysEcon SlotCourses 1 (red) CS 2 (Green) EE, Econ, Phys 3 (Blue) Math

Prof. Amr Goneid, AUC27 5. Representation Adjacency Matrix: V x V Matrix a(i,j) a(i,j) = 1 if vertices (i) and (j) are adjacent, zero otherwise. Usually self loops are not allowed so that a(i,i) = 0. For undirected graphs, a(i,j) = a(j,i) For weighted graphs, a(i,j) = w ij A D CB ABCD A0110 B1010 C1101 D0010

Prof. Amr Goneid, AUC28 Representation The adjacency matrix is appropriate for dense graphs but not compact for sparse graphs. e.g., for a lattice graph, the degree of a vertex is 4, so that E = 4V. Number of “1’s” to total matrix size is approximately 2 E / V 2 = 8 / V. For V >> 8, the matrix is dominated by zeros.

Prof. Amr Goneid, AUC29 Representation Adjacency List: An array of vertices with pointers to linked lists of adjacent nodes, e.g., The size is O(E + V) so it is compact for sparse graphs. A D CB C B D B A C AC ABD C

Prof. Amr Goneid, AUC30 6. Examples of Graph Algorithms Examples of Graph Algorithms: Graph Traversal Shortest Paths Minimum Cost Spanning Trees

Prof. Amr Goneid, AUC Graph Traversal Depth-First Search (DFS) Visits every node in the graph by following node connections in depth. Recursive algorithm. An Array val[v] records the order in which vertices are visited. Initialized to “unseen”. Any edge to a vertex that has not been seen is followed via the recursive call.

Prof. Amr Goneid, AUC32 Algorithm // Assume order = 0 initially void DFS() { int k; int unseen = -2; // Initialize all to unseen for (k = 1; k <= v; k++) val[k] = unseen; // Follow Nodes in Depth for (k = 1; k <= v; k++) if (val[k] == unseen) visit(k); }

Prof. Amr Goneid, AUC33 Algorithm (continued) void visit(int k) { int t; val[k] = ++order; for (t = 1; t <= v; t++) if (a[k][t] != 0) if (val[t] == unseen) visit(t); }

Prof. Amr Goneid, AUC34 Example A BCGF DE 1 VAL[K] ABCDEFG 1 start

Prof. Amr Goneid, AUC35 Example A BCGF DE 1 2 VAL[K] ABCDEFG 12

Prof. Amr Goneid, AUC36 Example A BCGF DE VAL[K] ABCDEFG 123

Prof. Amr Goneid, AUC37 Example A BCGF DE VAL[K] ABCDEFG

Prof. Amr Goneid, AUC38 Example A BCGF DE VAL[K] ABCDEFG

Prof. Amr Goneid, AUC39 Example A BCGF DE VAL[K] ABCDEFG

Prof. Amr Goneid, AUC40 Example A BCGF DE VAL[K] ABCDEFG

Prof. Amr Goneid, AUC41 Exercises Show how DFS can be used to determine the number of connected components in a graph. Explore the non-recursive version of the DFS using a stack. What will happen if you use a queue instead of the stack?

Prof. Amr Goneid, AUC42 Non-Recursive DFS // Assume unseen = -2 and hold = -1 // Val[ ] is set to “unseen” initially, order = 0 Stact S; // A stack of integers void DFS(int k) { int t;S.push(k); while (! S.stackIsEmpty()) { S.pop(k); val[k] = ++order; for (t = v; t >= 1; t--) // Scan from right to left if (a[k][t] != 0) if (val[t] == unseen) { S.push(t); val[t] = hold;} }

Prof. Amr Goneid, AUC43 Breadth-First Search (BFS) // Replacing the stack by a queue, gives the BFS algorithm Queuet Q; // A queue of integers void BFS(int k) { int t;Q.enqueue(k); while (! Q.queueIsEmpty()) { Q.dequeue(k); val[k] = ++order; for (t = 1; t <= v; t++) // Scan from left to right if (a[k][t] != 0) if (val[t] == unseen) { Q.enqueue(t); val[t] = hold;} }

Prof. Amr Goneid, AUC44 Example BFS A BCGF DE ABCDEFG

Prof. Amr Goneid, AUC45 DFS and BFS of a Tree For a tree structure: DFS is equivalent to Pre-order traversal BFS is equivalent to Level-order traversal DFS Demo BFS Demo

Prof. Amr Goneid, AUC46 natorica/animations/search.html mukundan/dsal/GraphAppl.html Graph Traversal Demos

Prof. Amr Goneid, AUC47 Exercise Model the shown maze asa graph. Show how DFS can be used to find the exit. in out

Prof. Amr Goneid, AUC48 8. A Simple Graph Class To represent a weighted undirected graph with a maximum of V max vertices and E max = V max (V max -1)/2 edges. The verices are numbered 0,1,...V-1. The graph is assumed to be on a text file in the form of an adjacency matrix. The weights on the edges are assumed to be positive integers with zero weight indicating the absence of an edge. When loaded from the text file, the weights are stored in a 2-D array (AdjMatrix) representing the adjacency matrix. Another array (edges) stores the non-zero edges in the graph. An edge (u,v,w) existing between nodes (u) and (v) with weight (w) is modeled as a class (Edge).

Prof. Amr Goneid, AUC49 Edge Class // File: Edge.h // Definition of Edge class #ifndef EDGE_H #define EDGE_H typedef int weightType;// weights are positive integers class Edge { public: int u,v;weightType w; bool operator < (const Edge &e) { return (w < e.w); } bool operator <= (const Edge &e) { return (w <= e.w); } }; // end of class Edge declaration #endif // EDGE_H

Prof. Amr Goneid, AUC50 Graph Class // File: Graphs.h // Graph library header file #ifndef GRAPHS_H #define GRAPHS_H #include #include "Edge.h" using namespace std; const int Vmax = 50; // Maximum number of vertices const int Emax = Vmax*(Vmax-1)/2; // Maximum number of edges

Prof. Amr Goneid, AUC51 Graph Class class Graphs { public: Graphs();// Constructor ~Graphs();// Destructor // Map vertex number to a name (character) char Vname(const int s) const; void getGraph(string fname);// Get Graph from text File (fname) void dispGraph( ) const;// Display Ajacency Matrix int No_of_Verices( ) const;// Get number of vertices (V) int No_of_Edges( ) const;// Get Number of Non-zero edges (E) void dispEdges( ) const;// Display Graph edges void DFS( );// Depth First Search Traversal (DFS)

Prof. Amr Goneid, AUC52 Graph Class private: int V, E;// No.of vertices (V) and edges (E) weightType AdjMatrix[Vmax][Vmax];// Adjacency Matrix Edge edges[Emax];// Array of non-zero edges int order;// Order of Visit of a node in the DFS int val[Vmax];// Array holding order of traversal void getEdges();// Get edges from adjacency matrix void printEdge(Edge e) const;// Output an edge (e) void visit(int k);// Node Visit Function for DFS }; #endif // GRAPHS_H #include "Graphs.cpp"

Prof. Amr Goneid, AUC Shortest Paths (General) In a graph G(V,E), find shortest paths from a single source vertex (S) to all other vertices. Edsger Dijkstra published an algorithm to solve this problem in 1959.

Prof. Amr Goneid, AUC54 Shortest Paths: Dijkstra’s Algorithm Dijkstra’s Algorithm for V vertices: Uses three arrays: - Distance[i]: holds distance from (S) to vertex (i). - Processed[i]: to flag processed vertices. - Via[i]: holds index of vertex from which we can directly reach vertex (i).

Prof. Amr Goneid, AUC55 Initialization Distance[i]: = 0if S = i = W si if (S, i) are adjacent =  otherwise Processed[i] = yes if i = S, No otherwise Via[i] = S if (i, S) are adjacent, 0 otherwise

Prof. Amr Goneid, AUC56 Method S z y x j i Already Processed Distance[j] Distance[i] Wij not yet processed closest to S adjacent to j

Prof. Amr Goneid, AUC57 Dijkstra’s Algorithm Repeat Find j = index of unprocessed node closest to (S) Mark (j) as now processed For each node (i) not yet processed: if (i) is adjacent to (j) then { new_distance = Distance[j] + W ij if new_distance < Distance[i] then { Distance[i] = new_distance ; Via[i] = j ; } } Until all vertices are processed

Prof. Amr Goneid, AUC58 InitialSource = A Example A E C B D A 0 A A 0 No yes 20  Dist Processed Via A B C D E

Prof. Amr Goneid, AUC59 j = B Example A E C B D A 0 A A 0 No yes 20  Dist Processed Via A B C D E

Prof. Amr Goneid, AUC60 j = Bi = D Example A E C B D A B A A 0 No yes Dist Processed Via A B C D E

Prof. Amr Goneid, AUC61 j = E Example A E C B D A B A A 0 yesNo yes Dist Processed Via A B C D E

Prof. Amr Goneid, AUC62 j = Ei = C Example A E C B D A B E A 0 yesNo yes Dist Processed Via A B C D E

Prof. Amr Goneid, AUC63 j = C Example A E C B D A B E A 0 yesNoyes Dist Processed Via A B C D E

Prof. Amr Goneid, AUC64 j = Ci = D Example A E C B D A B E A 0 yesNoyes Dist Processed Via A B C D E

Prof. Amr Goneid, AUC65 j = D Example A E C B D A B E A 0 yes Dist Processed Via A B C D E

Prof. Amr Goneid, AUC66 Final Example A E C B D A B E A 0 yes Dist Processed Via A B C D E A →B A→E →C A→B→D A→E

Prof. Amr Goneid, AUC67 How to print the path? /* The function Vname(k) maps a vertex number to a name (e.g a character A, B,.. etc). Given the via[ ] array resulting from Dijkstra’s algorithm, the following recursive function prints the vertices on the shortest path from source (s) to destination (i). */ void Graphs::printPath(int s, int i) const { if (i == s) cout << Vname(s); else {printPath(s,via[i]); cout << Vname(i);} }

Prof. Amr Goneid, AUC68 Demo binatorica/animations/dijkstra.html Shortest Paths Demo1 Shortest Paths Demo2

Prof. Amr Goneid, AUC Minimum Cost Spanning Trees (a) Spanning Tree Consider a connected undirected graph G(V,E). A sub-graph S(V,T) is a spanning tree of the graph (G) if: V(S) = V(G) and T  E S is a tree, i.e., S is connected and has no cycles

Prof. Amr Goneid, AUC70 Spanning Tree S(V,T): V = {A,B,C,D,E,F,G} T = {AB,AF,CD,DE,EF,FG} F E GA D CB

Prof. Amr Goneid, AUC71 Spanning Tree Notice that: |T| = |V| - 1 and adding any edge (u,v)  T will produce a cycle so that S is no longer a spanning tree (e.g. adding (G,D)) F E GA D CB

Prof. Amr Goneid, AUC72 One Graph, Several Spanning Trees

Prof. Amr Goneid, AUC73 For a connected undirected graph G(V,E), a spanning forest is S(V,T) if S has no cycles and T  E. S(V,T) will be composed of trees (V 1,T 1 ), (V 2,T 2 ), …, (V k,T k ), k ≤ |V| F E GA D CB Spanning Forest

Prof. Amr Goneid, AUC74 (b) Minimum Cost Spanning Tree (MST) Consider houses A..F connected by muddy roads with the distances indicated. We want to pave some roads such that: We can reach a house from any other house via paved roads. The cost of paving is minimum. This problem is an example of finding a Minimum Spanning Tree (MST) E G A B C F D

Prof. Amr Goneid, AUC75 Minimum Spanning Tree (MST) Cost: For a weighted graph, the cost of a spanning tree is the sum of the weights of the edges in that tree. Minimum Spanning tree: A spanning tree of minimum cost For the shown graph, the minimum cost is 22 E G A B C F D

Prof. Amr Goneid, AUC76 Kruskal’s Algorithm for MST The algorithm was written by Joseph Kruskal in 1956 A Greedy Algorithm: Builds the MST edge by edge into a set of edges (T). At a given stage, chooses an edge that results in minimum increase in the sum of costs included so far in (T). The set (T) might not be a tree at all stages of the algorithm, but it can be completed into a tree iff there are no cycles in (T).

Prof. Amr Goneid, AUC77 Kruskal’s Algorithm for MST Builds up forests, then joins them in a single tree. Constraints: - The graph must be connected. - Uses exactly V-1 edges. - Excludes edges that form a cycle.

Prof. Amr Goneid, AUC78 Abstract Algorithm - Form Set E of edges in increasing order of costs. - Set MST T = empty -Repeat Select an edge (e) from top. Delete edge from E set. Add edge (e) to (T) if it does not form a cycle, otherwise, reject. -Until we have V-1 successful edges.

Prof. Amr Goneid, AUC79 Example E G A B C F D Edge uvw accept 1EF2 2AC3 3CE3 4AE4 5CD4 6EG4 7DF5 8BD6

Prof. Amr Goneid, AUC80 Example E G A B C F D Edge uvw accept 1EF2yes 2AC3 3CE3 4AE4 5CD4 6EG4 7DF5 8BD6

Prof. Amr Goneid, AUC81 Example E G A B C F D Edge uvw accept 1EF2yes 2AC3 3CE3 4AE4 5CD4 6EG4 7DF5 8BD6

Prof. Amr Goneid, AUC82 Example E G A B C F D Edge uvw accept 1EF2yes 2AC3 3CE3 4AE4 5CD4 6EG4 7DF5 8BD6

Prof. Amr Goneid, AUC83 Example E G A B C F D Edge uvw accept 1EF2yes 2AC3 3CE3 4AE4 NO 5CD4 6EG4 7DF5 8BD6

Prof. Amr Goneid, AUC84 Example E G A B C F D Edge uvw accept 1EF2yes 2AC3 3CE3 4AE4 NO 5CD4yes 6EG4 7DF5 8BD6

Prof. Amr Goneid, AUC85 Example E G A B C F D Edge uvw accept 1EF2yes 2AC3 3CE3 4AE4 NO 5CD4yes 6EG4 7DF5 8BD6

Prof. Amr Goneid, AUC86 Example E G A B C F D Edge uvw accept 1EF2yes 2AC3 3CE3 4AE4 NO 5CD4yes 6EG4 7DF5 No 8BD6

Prof. Amr Goneid, AUC87 Example E G A B C F D Edge uvw accept 1EF2yes 2AC3 3CE3 4AE4 NO 5CD4yes 6EG4 7DF5 NO 8BD6yes

Prof. Amr Goneid, AUC88 How to test for Cycles? Simple Union- Simple Find Given a set (1,2,..,n} initially partitioned into n disjoint sets (each element is its own parent): Find (i): return the sub-set that (i) is in (i.e. return the parent set of i). Union (k,j): combine the two sub-sets that (j) and (k) are in (make k the child of j) Union builds up a tree, while find will search for the root of the tree. Cost is O(log n)

Prof. Amr Goneid, AUC89 How to test for Cycles? Represent vertices as Disjoint Sets Initially, each node is its own parent (-1) ABCDEFG ABCDEFG Let the parent set of u be p(u)

Prof. Amr Goneid, AUC90 How to test for Cycles? When edge (E,F) is selected, we find that p(E)  p(F). So, we make a union between p(E) and p(F), i.e., p(F) becomes the child of p(E). Same for edge (A,C) A BCDEFG ABCDEFG Parent table after selecting (E,F) then (A,C)

Prof. Amr Goneid, AUC91 How to test for Cycles? When (C,E) is selected, we find that P(C)  P(E). This means that the edge will be accepted. Select (A,E), Find will give P(A) = P(E) (cycle, reject). A BC D EFG ABCDEFG Parent table after accepting (E,F) then (A,C), then (C,E), then rejecting (A,E)

Prof. Amr Goneid, AUC92 How to test for Cycles? When (C,D) is selected, we find that P(C)  P(D). This means that the edge will be accepted. Select (E,G), Find will give P(E)  P(G) (accept). A BC D EF G ABCDEFG Parent table after 5 th accepted edge

Prof. Amr Goneid, AUC93 How to test for Cycles? When (D,F) is selected, we find that P(D) = P(F). This means that the edge will be rejected. Select (B,D), Find will give P(B)  P(D) (accept). A BC D EF G ABCDEFG Parent table after 6 th accepted edge (Final MST)

Prof. Amr Goneid, AUC94 Kruskal’s Algorithm 1. Insert edges with weights into a minimum heap 2. Put each vertex in a separate set 3. i = 0 ; 4. While ((i < V-1) && (heap not empty)) { 5. Remove edge (u,v) from heap 6. Find set (j) of connected vertices having (u) 7. Find set (k) of connected vertices having (v) 8. if ( j != k ) { i++; MST [i].u = u; MST [i].v = v; MST [i].w = w; 9. Make a Union between set (j) and set (k); } }

Prof. Amr Goneid, AUC95 Kruskal’s Algorithm Demo animations/mst.html Kruskal's algorithm at work on a graph of distances between 128 North American cities. Almost imperceptively at first, short edges get added all around the continent, slowly building forests until the tree is completed. MST (Kruskal) Demo1 MST (Kruskal) Demo2

Prof. Amr Goneid, AUC96 Learn on your own about: Directed Graphs or Digraphs Edge-List representation of graphs Prim’s algorithm for Minimum Spanning Trees. The algorithm was developed in 1930 by Czech mathematician Vojtěch Jarník Prim’s algorithm and later independently by computer scientist Robert C. Prim in 1957 and rediscovered by Edsger Dijkstra in Therefore it is also sometimes called the DJP algorithm, the Jarník algorithm, or the Prim– Jarník algorithm.