0% found this document useful (0 votes)
44 views

Graphs 10

Uploaded by

Tarzan Ghimire
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
44 views

Graphs 10

Uploaded by

Tarzan Ghimire
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 38
Representation and Application: Graph is a non-linear data structure. It contains a set of points known as nodes (or vertices) and a set of links known as edges (or Arcs). Here edges are used to connect the vertices. Agraph G can be defined as an ordered set G (V, E) where V (G) represents the finite and non- empty set of vertices and E(G) represents the set of edges which are used to connect these vertices. Example: - The following is a graph with 5 vertices and 6 edges, This graph G can be defined as G Where V = {A, B,C, D,E} and E PP ® @®. 47 Edge Vertices | ©) SO Graph terminologies: Vertex: An individual data element of a graph is called as Vertex. Vertex is also known as node. In above example graph, A, B, C, D & E are known as vertices. Edge: An edge is a connecting link between two vertices. Edge is also known as Arc. An edge is represented as (starting Vertex, ending Vertex).In above graph, the link between vertices A and. (V,E) {(A, B), (A, C)(A, D), (B, D), (C, D), (B, E), ( Bis represented as (A, B). Adjacent Vertices: Two vertices u and vin an undirected graph G are called adjacent in Gif u and v are endpoints of an edge e of G. Such an edge eis called incident with the vertices u and Vand eis said to connect u and v. Degree of Vertex: The degree of a vertex in an undirected graph is the number of edges incident with it A loop.at a vertex contributes twice to the degree of that vertex. The degree of the vertex v is denoted by deg(v). A vertex of degree zero is called isolated. A vertex with 4egree one is called pendant. Example: deg (A) = 3, deg (B) =3 dee (! 'n-degree: The in-degree of a vertex v is the number of edges that are incoming - towards v thead of edge)itis denoted by deg- (u) ; " (a Ouedesrees the out-degree of a vertex vis the number of edges that are outgoing from v {tail ot “t2).tis denoted by dest (u). rode tay | Destu) Degt(u) > |. ? 3 | | r—7 OT 2 1 1 3 3 1 4 2 0 Types of Graph: © Directed Graph: © Ina directed graph, the connection between two nodes is one-directional. 0. Itisa graph in which each edge has a direction to its successor. © Itisa graph with only directed edges. + Undirected Graph: © Inanundirected graph, all connections are bi-directional. ©. Itisa graph in which there is no direction on the edges. The flow between two vertices can go in either direction, Connected Graph: An undirected graph is called connected if usd 'sapath between every pair of distinct vertices of the rap! * Not-Connected Graph: An undirected graph that is not connected is called disconnected Example Gis the connected eraph becuse fo every pi of distinct vrtices thar isa path betwen hem and G2 isthe no-coancted raph bacuse there no path between vertices wand d. @ b a b . e « — | ad t oy G: * Strongly Connected Graph: A directed graph is strongly connected if there is @ path from A to B and from B to A whenever A and 8 are vertices in the graph. * Weakly Connected Graph: A directed graph is weakly connected if there is a path between every two vertices in the underlying undirected graph. That is, a directed graph is weakly connected if and only if there is always a path between two vertices when the directions of the edges are disregarded. (=) @) aa, aa, ese Gee c Weakly Connace Connetod Complete Graph: CS, () * Agraph in which any V node is adjacent to all other nodes present in the graph is known as a complete graph. An undirected graph contains the edges that are equal 2 @) edges = n(n — 1)yRere nis the number of vertices Acomplete graph. Present in the graph. The following figure shows a complete graph. Xesular Graph; ach other, ie., each node is accessible nt to ee ' jacel Itis the graph in which nodes are adj ° itis from any other node. a i rst and last nodes are the ae sna cyleis called cycle graph. In this case the first an © Agraph having cyc! 5 same. Aclosed simple path is a cycle. ic graphs. eye eh oS G) (ey (@) Weighted Graph: (2) @) (4) 1 ‘Acyclic Graph: A graph without cycle is called acycl quer * Graphs that have a number assigned to each edge are called weighted graphs. * Inaweighted graph, each edge has an associated numerical value, called the weight of the edge. Edge weights may represent distances, costs, etc, Example: In a flight route graph, the weight of 8 an edge represents the distance in miles between the endpoint airports Planar Graph: Representation of Graphs; : 4, Adjaceney matrix init, we have a matrix of order n*n where n is the number of nodes in the graph. ‘The matrix represents the mapping between various edges and vertices. inthe matrix, each row and column represents a vertex. The values determine the presence of edges. ; Let Aij represents each element of the adjacency matrix. Then, For an undirected graph, the value of Ajj is 1 if there exists an edge between i and j. Otherwise, the value of Aijis 0. AB COD afoo1 04 By 1 0 4 4 c]o 1 0 4 pb} 1 7641 0 Adjacency matrix * For adirected graph, the value of Aijis 1 only if there is an edge from i to jie. iis the initial node and j is the terminal node. A B CD aAfo 0 0 0 bB} 1 0 9 4 clo 1 0 0 Dy} 1 Directed graph or 6 Adjacency matrix * The time complexity of the adjacency matrix is O(n?). 2 Adjacency lis i adjacency list is an array of linked lists where the array denotes the total vertices each linked list denotes the vertices connected to a particular node. * inalingea p ; sini’ lst, the most important component is the pointer named ‘Head’: because this ae pee maintains the whole linked list. For linked list representation, we will have ters equal to the number of nodes in the graph. - Foran un di aT ode ag tom 8raph, we will link all the edges in the list that are connected toa pear Undirected graph Adpcenn) Ust «© Inadirected graph, we will link only the initial nodes in the list as shown: si ly i 7 © Directed graph Adjaceney List Applications of Graph In Computer science graphs are used to rey Google maps uses graphs for building tran: where intersection of two(or more) roads are considered to be a vertex and the road connecting two vertices is considered to be an edge, thus their navigation system is based on the algorithm to calculate the shortest path between two vertices, Computer networks: Local area network, ‘present the flow of computation. 'sportation systems, undirected graph, In World Wide Web, web Pages are considered to be the vertices. There is an edge from ® page u to other page y if there is a link of Page v on page u. This is an example of Directed graph. itwas the badie idea behing Google Page Ranking Algorithm. Transitive closure: Transitive Closure it the reachability matrix to reach from vertex u to vertex v of a graph One graph is given, we have to find a vertex v which is reachable from another vertex u, for all vertex pairs (u, v), It states if there is a path from vertex a to b then there should he an edge from a to b. For finding transitive closure of a graph Add an edge from a to cif there exists a path from a to b and b toc Repeat this process of adding edge until no new edges are added. Hence, it can be defined as, If G=(V,) in a graph then its transitive closure can be defined as G*=(V,E*) where E*={(Vi,Vj): there exists a path from Vi to VjinG} Transitive Closure of a Directed Graph Given a directed graph, find out if a vertex is reachable from another vertex forall vertex pairs (i,j) in the given graph, Here reachable mean that there is a path from vertex ito j, The reach-ability matrxis called the transitive closure of a graph Transitive closure js also stored as a matrix T, so if T[1J[5] = 1, then node 5 can be reached from node 4 in one or more hops. @ See Bde (b) (a) A graph G and its (b) transitive closure G* For example, consider below graph is osure of above graphs d transitive diagraph: 's algorithm for finding transitive closure from (to elements of Ri is: (LK) and ROAD Warshall’ ence relating elements R ROL] = ROLL OF rules for generating R™ from Rie: in RO, itremains tin RY i) it has to be changed to tin RW" if d the element in its column j and.row Recurr + Itimplies the following. Rule If an element in row i and-column jis 4 Rule? If an element in row iand colurnn jis Oin Rt ‘and only if the element in its row i and column k an kare both 1'sinR™. ngsplemenits Warshall’s algori puititig the (Mingut: The adjacency mattix'A of @ digray f ’ ph with n-vert YOutput: The transiti t ips ie. tive closure of the digraph fork-1t6 nda for 1tonde Yor 3 Hote ont. Tee REM tae) ‘The mai rived s 'e main idea of these graphs is described as fol lows; een he vertices i | will be contained a path if The Graph contains an edge from i toj: + “The graph contains a ae ° Path from ito j wit ‘The graph contains a path from itolean we veto RDA (path using just 1 ,--.,f-1) or ; ki, A] 2 DK j}) (path from 7 tok i al wD and from kto7 using just 1 gereght-l) ROUAL= ik iteration. ma AR = 1 Fig: Rule for changing zero’s in Warshall's Algorithm Example 1: (2) (6) abed abed \ afo-1 00 afi 141} bjoo001 blr 144 A= Glo 0 0 0 ™ lo 00 0 G (4) dl1010 dli 144 (a) (b) © {a) Digraph. (b) Its adjacency matrix. (c) Its transitive closure. Figure. Example 2: Warshall's algorithm to find the transitive closure of the digraph define d by the following, Apply adjacency matrix. , 0100 oo10 ooo1 0000 Applying Warshall’s algorithm yields the following sequence of matrices $ 100 (0) 010 malo 004 oLid ooo090 roo} 04a 4 000 1 02100 00.060 ro] 8 09 1.0 ooo01 0000 OL.ia2i oii2080 rR} 9 O17 ro.|9 0 1:0 00014727 oago01 0 0.00 0 a 0 0 Traversing Graph: yga vertex in earchir sd for search na. grap nad der of vertices is Vi ‘ed in the search sal isa technique . aph travel - oo also used i decide the 0} «The graph traversal is Jto search process without creating “ e used in the z ne finds the edges 0 De the vertices of the graph without + Agraph traversal etal ae “That means using graph traversal We ing i ing path. getting into looping P | «There are two graph traversal techni 4. DFS (Depth First Search) 2, BFS (Breadth First Search) iques and they are as follows: DFS (Depth First Search): DFS traversal of a graph produces a spanning tree as final result. Spanning Tree is a graph without loops, We use Stack data structure with maximum size of total number of vertices in the graph to implement DFS traversal. We use the following steps to implement DFS traversal... Step 1 - Define a Stack of size total number of vertices in the graph. Step 2 - Select any vertex as starting point for traversal, Visit that vertex and Push it on to the Stack. Step 3 - Visit any one of the non-visite: 'd adjacent verti ; the top of stack and push it on to the tices of a vertex which is at stack, Step 4-Repeat step 3 until there i he verte isno isi ehatte oer e New vertex to be visited from the vertex Step 5 - When there is no ne 0 visit hy mi one W vertex to visi Reet nee * to visit then use back tracking and pop step 7 -When stack becomes Empty, hen produce final spanning tree by removing unused edges from the graph Example 4: Consider the folowing example graph to perform DFS traversal step 3: = Select the vertex A as starting point (visit A). Push A on to the Stack, |_| A Stack step 2: ~ Visit any adjacent vertex of A which is not visited (8) |_| ~ Push newly visited vertex B on to the Stack. B LA] Stack = Visit any adjacent vertext of B which Is not visited (C). Push Con to the Stack. |. sa Visit any adjacent vortext otc which is not visited (e). = Push E onto the Stack Stop 5: . “Visti any-adjacent vertext of E which Is not visited (D), ~ Push D on to the Stack Step 6: ~ There'ls no new vertiex to be visited from D, So use + Pop D from the Stack, back fash ‘Step 7: i Pll] 1 2B s 8 > ELL] m1 PE a B a | LT Stack ~ Visit any adjacent vertex of E whic it “Pal ay aac vie of which evista Stack FePEl | Stop 8 a = Visit any adjacent vertex of F which is not visited (4). = Push G on to the Stack. Step 9: + There is no new vertiex to be visited from G, So use back track. ~ Pop G froin the Stack Step 10: ~ There is no new vertiex to be visited from F. So use back track, = Pop F from the Stack. Step 11; ~ There is no new vertiex to be visited from E. So use back track, ~ Pop E from the Stack, >|=[9|=[=]o 2 g 5 = PEEEE i B 5 = Elle TT] gel TT = Fy a e | ce track, : isi €.S0 use back trad Ste? exes no ne vertex to be visited from = Pop C from the Stack. bend B A Stack: Step.13; Spa Theres no ne veto tobe vised fom B, So use back rack, ~ Pop B from the Stack, [x] Stack. Step 14; ~ There is no new vertiex tobe visited from A. So use-back track, Pop A from the Stack, tack ~ Stack became Eimply. So stop DFS Treversal, ~ Final result of DFS traversal is following spanning tree, BFS (Breadth First Search) / . inal resi ee is a gra BFS traversal of a graph produces a spanning tree as final result. aa tree ae without loops. We use Queue data structure with maximum size of total number of vertices in the graph to implement BFS traversal, We use the following steps to implement BFS traversal Step 1 - Define a Queue of size total number of vertices in the graph. Step 2 Select any vertex as starting point for traversal. Visit that vertex and insert it into the Queue. Step 3 - Visit all the non-visited adjacent vertices of the vertex which is at front of the Queue and insert them into the Queue. Step 4- When there is no new vertex to be visited from the vertex which is at front of the Queue then delete that vertex. Step 5 - Repeat steps 3 and 4 until queue becomes empty. Step 6 - When queue becomes empty, then produce final spanning tree by removing unused edges from the graph Example 1: Consider the following example graph to perform BFS traversal Step 4; © + Select the vertex A as startin olnit (visi Insert into the Queue, mA Queve jsited (D, EB). arenotvisted EP ne queue. Queue and delete A Ppt sort i tices of A i _ visit all adjacent vertiCe™ penn sited vertices Into the rit all adjacent vertices of D which are not visited (there is NO verter). Delete D from the Queve, Queue 7 E which are not visited (C, F)- into the Queue and delete E from the Queue. . pa: + Visit all adjacent vertices of Insert newly visited vertices Queue (Life hare not visited (there is no vertex). - Visit all adjacent vertices of B whic = Delete B from the Queue, Queue PLL Ste llajacon votes of C wich are not vite ue, = Insert ely visited vertex into the Queue and delete € from the Queue, Queue - Visitall adjacent vertices of F which are not visited (there is no vertex). + Delete F from the Quetia, ~ Visit all adjacent yertices of @ whicl +h are not visited (there is ino vertex), ~ Delete G from the Queue, Z Queue: ooo 7 Queue became Einply, So, stop the BFS protess, ~ Final result of BFS.is a Spanning Tree as shown below. Topological Sort * Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering, of vertices such that for every directed edge u v, vertex u comes before v in the ordering, Topological sorting for a graph is not possible if the graph is not a DAG. Topological Sort using Depth First Search (DFS) ° Use temporary stack to store the vertex. Maintain a visited [] to keep track of already visited vertices. In DFS we print the vertex and make recursive call to the adjacent vertices but here we will make the recursive call to the adjacent vertices and then push the vertex to stack. Observe closely the previous step, it will ensure that vertex will be pushed to stack only when all of its adjacent vertices (descendants) are pushed into stack. Finally print the stack. For disconnected graph, Iterate through all the vertices, during iteration, at a time consider each vertex as source (if not already visited). spt, Tlf ee)eewe gp oe ett Liisenpp ine enc Aetbeny Kone «a [ oa (LT spk Tpit stezTetwe gage yeaa ate Teli it] te] a aend ited Nomar ‘Sak vfsops ii 0 4 | today vated Nomare renin at ef ve fhe fe eee orb st PT BT? sate) sep pdigalssitspene sey ——_‘Nialeense a aati teen + For example, alent Noreen at ot PEED a topological sorting ofthe following graph is "5 42.9 10" «There can be more than one topological sorting for a graph. 16 "45 0". i jing graph is "45234 © For example, another topotogical sorting of the following 6 pI ‘or example, a * For example, a topological sorting of the following graph is “A BEF DC". © There can be more thaf one topological sorting for a graph. Topological Sort using Breadth First Search (BFS) For that, we will maintain an array T[ J, which will store the ordering of the vertices in topological order. We will store the number of edges tha€ are coming into a vertex in an array in_degree[N], where the i-th element will store the number of edges coming into the vertex i. We will also store whether a certain vertex has been visited or not in visited| vil follow the below ste [IN]. We First, take out the vertex whose coming into that vertex. jetée'ls 0. That means there is no edge that is ‘We will append the vertices in the Queue and mark these vertices as vi Now we will traverse through the queue and in each step we will dSgUis element in the Queue and push it into the T. mw Similarly, for those vertices whose iftagar fs 0, we iti ‘mark that vertex as visited, : will push it in Queue and also step 1 Queue =[1] Stop 2 Queue =[2] Step3 Queue =[4] Step 4 Queue =[3] step 5 Queue =[5] Step 6 Queue =[] In_degreet In_degreol } In degreet] Indegreet] in.degreot) | 0 In.degreet} Not Visited visited T o Te[1] T=[1,2,4] T=[1,2,4,3] TSI1,2,4,3,5] Minimum Spanning Tree: Example Example 2: Given a connected and undirected graph, a spanning tree of that graph is a subgraph that isa tree and connects all thé vertices together and the graph doesn’t have any nodes which loop back to itself. single graph can have many different spanning trees. A minimum spanning tree (MST) or minimum weight spanning tree for a weighted, connected and undirected graph is a spanning tree with weight less than or equal to the weight of every other spanning tree. ‘The weight of a spanning tree is the sum of weights given to each edge of the spanning tree In real-world situations, this weight can be measured as distance, congestion, traffic load or any arbitrary value denoted to the edges. The total number. of spz 25 ing trees with plvertices that can be created froma'complete. graph is equal to “Aminimum spanning tree has (V - 1) edges where V is the’number of vertices in the given graph. tas + Biaph meted trea ee 1p Misitinuin sp: ‘Tree, Costs 7 anni Example 3: Kruskal’s algorithm: Below are the steps for finding MST using Kruskal’s algorithm Step 4: Remove all loops and parallel edges. In case of parallel edges, keep the one which has the least cost associated and remove all others, Step 2: Arrange all edges in their increasing order of weight Step 3; Pick the smallest edge. Check if it forms a cycle with the spanning tree formed so far. If cycle is not formed, include this edge. Else, discard it. Step 4: Repeat step 3 until there are (V-1) edges in the spanning tree. Example 4: + Remove all loops and parallel edges. In case of parallel edges, keep the one which has the least cost associated and remove all others. Arrange all edges in their increasing order of weight. Cre ate a set of edges and weight, and arrange them in an ascending order of weightage (c ost). tt Now we start adding edges to the graph beginning from the one which has the least weight, Throughout, we shall keep checking that the spanning pro erties remain intact, Incase, by adding one edge, the spanning tree property does not hold then we shalt consider not to include the edge in the graph. on and we observe that adding it will create a circuit in the Next cost in the table is 4, all edges that create a graph. -We ignore it. In the process we shall ignore/avoid circuit. We observe that edges with cost 5 and 6 also create circuits. We ignore them and move on By adding edge S,A we have included all the nodes of the graph and we now have minimum cost spanning tree. Prim's Algorithm is a greedy algorithm that is used to find the minimum spanning tree from a graph. Prim’s algorithm finds the subset of edges that includes every vertex of the graph such that the sum of the weights of the edges can be minimized. Prim’s algorithm starts with the single node and explores all the adjacent nodes with all the connecting edges at every step. The edges with the minimal wei ights causing no cycles in the graph got selected, The steps to implement the prim's algorithm are given as follows - © First, remove all loops and parallel edges and we have to initial randomly chosen vertex. ‘ave to find all the edges that connect the tree in the above step with the new o Now, we hi vertices. From the edges found, select the minimum edge and add it to the tree. fo Repeat step 2 until the minimum spanning tree is formed. Example 1: Remove all loops and parallel edges from _ the given graph. In case of parallel edges, keep the one which has the least cost associated and remove all other node as root node: Choose any arbitrary In this case, we choose $ node as the root node of Prim's spanning tree. This node is arbitrarily chosen, so any node can be the root node. One may wonder why any nade can be a root node. So the answer is, in the spanning tree all the nodes of a graph are included and because it is connected then there must be at least one edge, which will join it to the rest of the tree. Now, the tree ean is treated as one node and we check for all edges going out from it. We select the one which has the lowest cost and include it in the tree i.e., $-7-A-3-C, eine Example 2: (0) Original graph (bi) “Alter the First edge has sen selegtell {@ Afierthe second edge: his been selécted (d) Final minimum: spanning tfee ay a b wa he atl Qemes at] Sea Ze wows gain 8 wole- 28 owbe 8 8 8 ew S = a g-Nowu gor D1 +g isis = BiB Round Robin Algorithm: This method provides better performance when the number of edges is low. Initially each node is considered to be a partial tree. Each partial tree is maintained in a queue Q. Priority a their weights. The algorithm proceeds by removing a partial tree, T1, from the front of Q, finding the minimum weight arc a in T1; deleting from Q, the tree T2, at the other end of arc a; combining T4 and 72 into a single new tree T3 and at the same time combining priority queues of T1 and T2 and adding T3 at the rear of priority queue. ie is associated with each partial tree, which contains all the arcs ordered by * This continues until Q contains a single tree, the minimum spanning tree. Q Priority. queue {A} A) {cy {D} 24,5 {5} 3,5 4 2 Q Priority queue {E} 3.5 {A.C} (2.3.4 {B.D} | 2.3,3,4.5 Q Priority queue | en FAGEBD} |3,3.44,5,5 Q Priority queue (ACh 1234 ¥E,B,D} [23,455 Only 4 partial tree is left in the queue, which is the required minimum spanning tree. Shortest path algorithm Greedy Algorithm: A greedy algorithm is a simple, intuitive algorithm that is used in optimization problems. The algorithm makes the optimal choice at each step as it attempts to find the overall optimal way to solve the entire problem, It follows local optimal choice of each stage with intend of finding global optimum. Greedy algorithms are quite successful in some problems, such as Huffman encoding which is venta compress data, or Dijkstra's algorithm, which is used to find the shortest path through a graph. pijkstra’s shortest path algorithm Given a graph and a source vertex in the graph, find shortest paths from source to all vertices the given graph. ‘ uo” Algorithm, 4. create a set sptSet (shortest path tree set) that keeps track of vertices included in path tree, Le., whose minimum distance from source is calculated and finalize. Initially, isempty. 2, Assign a distance value to all vertices in the input graph. initialize all distance values as INFINITE. Assign distance value as 0 for the source vertex so that it is picked first 3, While sptSet doesn't include all vertices a) Pick a vertex u which is not there in sptSet and has minimum distance value. b) Include u to sptSet. ¢) Update distance value of all adjacent vertices of u. To update the distance values, iterate through all adjacent vertices. For every adjacent vertex v, if sum of distance value of u (from source) and weight of edge u-v, is less than the distance value of v, then update the distance value of v. RELAX(u, Vv, W) > (Maybe) improve our ‘estimate of the distance to v > by considering a path along the edge (u, ¥) if fu] + w(u, v) < of] then fy] <— afuy+ w(u, v) > actually, DECREASE-KEY aly] <—u > remember predecessor on path we'll compute shortest paths from A < Cs) af ‘ TRIER IS ar eT

You might also like