Download as pdf
Download as pdf
You are on page 1of 41
UNIT V GRAPH STRUCTURES 5.1 $5.2 5.3 5.4 5.6 Definition Representation Of Graph Types Of Graph 5.3.1 Applications of Graph Graph Traversal 5.4.1. Breadth First Search (BFS) 5.4.2 Depth First Search (DFS) Directed Acyclic Graph—Topological Ordering 5.5.1 Steps for implementing the topological sort 5.5.2 Applications of Topological Ordering Minimum Spanning Tree (MST) 5.6.1 Properties of spanning trees 5.6.2 Minimum Spanning Tree(MST) 5.7 Algorithm: Minimum cost path Two Marks Question and answers Review Questions 5.1 5.1 5.3 5.6 5.7 5.7 5.1L 5.14 5.14 5.21 5.21 5.21 5.22 5.33 5.37 5.40 Graph Structures 5.1 UNIT V GRAPH STRUCTURES 5.1. DEFINITION Graph A graph G = (V, E) consists of a set of vertices, V, and a set of edges, E. Vertices are referred to as nodes. The arcs between the nodes are referred to as edges. Each edge is a pair (v,w), where v,w € V. Edges are sometimes referred to as arcs. (s) Xl Fig 5.1: Graph In the graph, V,, V>, V3, V, are the vertices (V1, Va)s(Va Va )s(V 55 Vas(Vas Vs(V, V3) (VeV,) are edges 5.2 REPRESENTATION OF GRAPH Following two are the most commonly used representations of graph. 1. Adjacency Matrix 2. Adjacency List There are other representations also like, Incidence Matrix and Incidence List. ‘The choice of the graph representation is situation specific. It totally depends on the type of operations to be performed and ease of use. Data Structures Design 1, Adjacency Matrix 1 matrix with n rows and n A graph containing n vertic be represented by columns, The matrix formed by storing the edge weight in its ith row and jth column of the matrix, if there exists an edge between ith and jth vertex of the graph, and 0 if there are no edges to itself and oo if there are no edges between ith and jth vertex of the graph, such a matrix is referred as an adjacency matrix. Adjacency matrix for directed graph Adjacency matrix for undirected graph Adjacency matrix for weighted graph Graph Structures 5.3 2. Adjacency List A graph containing m vertices and n edges can be represented using a linked list, referred to as adj jacency list. The number of vertices in a graph forms a singly linked list. Each vertex have a Separate linked list, v with nodes equal to the number of edges connected from the Corresponding vertex. ~ 4 +34 2 Ee PEG : + BEE E+-a a ry 6 en, 1. Directed Graph (or) Digraph = = 5.3 TYPES OF GRAPH Directed graph is a graph, which consists of di E is unidirectional. In directed called as digraphs. If (v,W) is a irected edges, where each edge in graph, the edges are directed or one way. it is also directed edge, then (v,w) # (w,v). Fig 5.2: Directed graph (V4, Va) * (Va. V4) 2. Undirected Graph An undirected graph is a graph, which consists of undirected edges. In undirected graph, the edges are undirected or two way. If (v,W) is a undirected edge. then (v,w) = “ Q—® (V4, Va) = (Va. V4) Fig 5.3: Undirected graph Data Structures Design 3. Weighted Graph [A graph is said to be weighted graph if every edge in the graph is assigned a weight or value. It can be directed or undirected Fig 5.4.(a). Weighted Grapi: (Uirected) Fig 5.4.(b) Weighted Graph (Undirected) 4. Complete Graph s a graph in which there is an edge between every pair of A complete graph i /2. A complete graph is a vertices. A complete graph with n vertices will have n(n-1), strongly connected graph. O89) of oe © © Fig 5.5 (a) Complete graph Fig 5.5. (b). Vertices of a graph 5. Strongly connected Graph ; If there is a path from every vertex to every other vertex in a directed graph then it is said to be strongly connected graph. Otherwise, it is said to be weakly connected graph. Fig 5.6: Strongly Connected Graph Fig 5.7: Weakly connected graph Graph Structures 55 6. Path A path in a graph is defi ned as a sequence of verices w,, Wy, Wy... , W, such that, (W), W2, W3, . -) €E, where E is the number of edges in a graph, Simple Path A simple path is a path such that all vertices are distinct (different), except that the first and last vertexes are same. 7. Cycle A cycle in a graph is a path in which the first and the last vertex are the same. Fig 5.8: Cycle 8. Cyclic Graph A graph which has cycles is referred to as cyclic graph. A graph is said to be cyclic, if the edges in the graph should form a cycle. 9. Acyelie Graph A graph is said to be acyclic, if the edges in the graph does not form a cycle. Fig 5.9: Acyclic graph 5.6 Data Structures Desi == 10. Directed Acyclic Graph (DAG) A directed graph is acyclic if it has no cy' as Directed Acyclic Graph. cles, and such types of graph are calle=—=—= 11. Degree The numb« she vertex V is written as degree (V). cr of edges incident on a vertex determines its degree. The degree <= Indegree : The indegree of the vertex V, is the number of edges entering into th vertex V. outdegree of the vertex V, is the number of edges exiting fron: Of 660 Fig 5.10: Graph for calculating indegree and outdegree Outdegree: The the vertex V. Indegree of vertex V, = 2 Outdegree of vertex V, = 1 Indegree of vertex V, = 1 Outdegree of vertex V, = 2 5.3.1 Applications of Graph Graphs are constructed for various types of applications such as: « Incircuit networks where points of connection are drawn as vertices and component wires become the edges of the graph. e _ Intransport networks where stations are drawn as vertices and routes become the edges of the graph. « In maps that draw cities/states/regions as vertices and adjacency relations as edges. Graph Structures 57 In program flow analysis where procedures or modules are treated as vertices and calls to these procedures are drawn as edges of the graph. Once we have a graph of a particular concept, they can be easily used for finding shortest paths, project planning, etc. In flowcharts or control-flow graphs, the statement: Program are represented as nodes the edges. In state transition diagré and the edges represent legal mor 's and conditions in a and the flow of control is represented by ‘ams, the nodes are used to represent states ves from one state to the other, ¢ Graphs are also used to draw activity network diagrams. These diagrams are extensively used as a project mana; gement tool to represent the interdependent relationships between roups, steps, and tasks that have a si ignificant impact on the project. 5.4 GRAPH TRAVERSAL Graph traversal is a technique used for searchi | traversal is also used to decide the order of vertic | graph traversal finds the edges to be used in the s. | That means using graph traversal we visit all the | into looping path. ing a vertex ina graph. The graph es is visited in the search Process. A earch process without creating loops. vertices of the graph without getting There are two graph traversal techniques and they are 1. DFS (Depth First Search) 2. BFS (Breadth First Search) 5.4.1. Breadth First Search (BFS) ¢ Breadth First Search (BFS) of a graph G starts from an unvisited vertex u. ¢ Then all unvisited vertices v, adjacent to w are visited and then all unvisited vertices w, adjacent to vi are visited and so on. The traversal terminates when there are no more nodes to visit. BFS uses a queue data structure to keep track of the order of the nodes whose adjacent nodes are to be visited. Steps to Implement BFS 1. Select the start vertex and mark it as Visited (i.e) place the value 1. 2. _Enqueue the START vertex. 58 Data Structu-—— Dequeue the vertex. Find all adjacent unvisited vertices of the dequeued vertex. Mark all unvisited adjacent vertices as visited. os 2 Enqueue all adjacent vertices. 7. Repeat from step 3 to step 6 until the queue becomes empty. VI enqueue( ) ABDC Example: Dequeve( ) ABDC output: ABDC Step by Step BFS Traversal for Graph Step 1: Start with the root vertex. Let us consider A as root vertex. ® Vertices enqueue( ) A Dequeue() A Mark the root vertex A as visited (1), enqueue() the vertex A and dequeusaa Step 2: Find the adjacent unvisited vertices of the dequeued vertex A. nqueue( ) AB D ©) : Dequeue( ) A B Graph Structures 5.9 Mark the unvisited adjacent vertices B and D as visited, enqueue() the adjacent vertices B and D and dequeue() vertex B . Step 3: Find the adjacent unvisited ve visited, it is not considered. enqueue() vertex C, and mark it as visited ertices for vertex B. Notice that since D is enqueue() ABDC Dequeue() AB Step 4: dequeue() the vertex D. There are no unvisited adjacent vertices to vertex D because all the adjacent vertices are visited. enqueue( )ABD © Dequeue() AB D Step 5: dequeue() the vertex C, There are no unvisited adjacent vertices to vertex low all the vertices of the graph are visited. Therefore BES ends, The BFS order is ABD C CN enqueue’ ABDC Dequeue()ABDC 5.10 Data Structures Ox Python code for BFS [graph = ( ‘SEZ 7), S30: (2 as 7 EB), 2:0 (8), 8: } visited = [] # List for visited nodes. queue = [] #Initialize a queue def bfs(visited, graph, node): #function for BFS visited.append(node) queue.append(node) while queue: # Creating loop to visit each node m = queue.pop(0) print (m, end = “ “) for neighbour in graph[m]: if neighbour not in visited: visited.append(neighbour) queue.append(neighbour) # Driver Code print(“Following is the Breadth-First Search”) bfs(visited, graph, ‘S’) # function calling OUTPUT Following is the Breadth-First Search 537248 Graph Structures 5.11 5.4.2 Depth First Search (DFS) ¢ Visit the first node initially, and then find the unvisited node which is adjacent to the first node, is visited and a DFS is initiated from the adjacent node (considering it as the first node). * — Ifall the adjacent nodes have been visited, backtrack to the last node visited, and find another adjacent node and again initiate the DFS from adjacent node. + This traversal continues until all nodes have been visited once. Steps to Implement DFS 1, Select the start vertex 2. Visit the vertex (place 1) 3. Push the vertex on the stack 4. pop the vertex 5. find the adjacent vertices and find any one of the unvisited adjacent vertex 6. repeat from step 2 to 5 until the stack becomes empty | Example: Step by Step DFS Traversal for Graph Data Structures 5.12, Step 1: Let us start with the root vertex A. Mark the vertex A as visited. push the vertex A into the stack and pop it Step 2: Find the unvisited adjacent vertices of the popped vertex A. d| Output: AC Either C or B can be selected as unvisited adjacent vertex. Let us select v= Mark the vertex C as visited. push the vertex C into the stack and pop it out. Step 3: Find the unvisited adjacent vertices of the popped vertex C. (c) (0) Visited A B Cc D (2) Output: ACB Notice that vertex A is not considered, since it is visited. Either B or D selected. Let us select vertex B. Mark the vertex B as visited. push B into the t= pop it out. Graph Structures 5.13 Step 4: Find the unvisited adjacent vertices of the Popped vertex B. (0) [ Wertces | Visited] Push] A B Cc D A B c D Notice that vertex C and A are not considered, since they are visited. Mark the vertex D as visited. push D into the stack and Pop it out. Output: ACBD Step 5: Since all the vertices of D are visited, and visited, DFS ends. The output is the order in which t Output: ACB D. all the vertices in the graph are the vertices are Popped out. Python code for DFS # Using a Python dictionary to act as an adjacency list graph “5? [53,7], oie le2e ea ‘Ts [68°], 2:0) ‘4 :[8}, 820 ) visited = set() # Set to keep track of visited nodes of graph. def dfs(visited, graph, node): #function for dfs if node not in visited: print (node) visited.add(node) for neighbour in graph[node]: dfs(visited, graph, neighbour) # Driver Code S14 Data Structure——— print(*Following is the Depth-First Search”) dfs(visited, graph, *5”) OUTPUT 5.5 DIRECTED ACYCLIC GRAPH—TOPOLOGICAL ORDERING A topological sort is an ordering of vertices ina directed acyclic graph, ss if there is a path from vi to vj, then vj appears after vi in the linear ordering, 5.5.1 Steps for implementing the topological sort Step 1: Find the indegree for every vertex. Step 2: Place te vertices whose indegree is 0 on the empty queue. Step 3: Dequeue the vertex V and decrement the indegree s of all its == vertices. Step 4: Enqueue the vertex on the queue, if its degree falls to zero. Step 5: Repeat from step 3 until the queue becomes empty. The topological ordering is the order in which the vertices dequeued. Example I: Vertices Graph Structures 5.15 Example 2: Vertices Indegree Step by Step Topological sort for Example 1: Step 1: Find the Indegree of vertices 1,2,3,4,5,6. Indegree of a vertex is the number of edges entering into the vertex. Indegree of vertex 1 is 0, vertex 2 is 0, Vertex 3 is I, vertex 4 is 3, vertex 5 is 1, vertex 6 is 3. Vertices Indegree enque() Dequeue() e vertices with Indegree 0. Therefore enqueue() vertices 1 Step 2: enqueue() th and 2. ; Vertices 5.16 Data Structures Step 3: dequeue() vertex 1 and find all the adjacent vertices. The adjacent v— are 3 and 4. Therefore decrement the Indegree of the adjacent vertices 3 and 4 Indegree Vertices Dequeue() Indegree 0 0 1 3 1 3) Step 5: Find the adjacent vertices of vertex 2. Decrement the Indegree <— adjacent vertices 4 and 5 by 1. Graph Structures 5.17 Step 6: enqueue() the vertex 5 since its indegree is 0. dequeue() the vertex 3, Vertices Step 7: Find the adjacent vertices of tl Indegree of the vertices 4 and 6 by 1. he dequeued vertex 3. Decrement the Dequeue( ) Step 9: Find the adj Of the vertex 6 by 1. jacent vertices of the dequeued vertex 5. Decrease the Indegree 5.18 Data Structures 1 Indegree 6 12 Step 10: dequeue() the vertex 4 whose Indegree is 0 and find the adjacent of the vertex 4. Vertices Indegree 1 0 2 0 3 1 4 3 5 1 6 3 enque( ) Dequeue( ) Step 11: Decrement the Indegree of the vertex 6 by 1. 1 0 a 0 3 1 4 3) : 1 3 [enact [23 TS | [Bequeuer [1] Graph Structures 5.19 Step 12: enqueue() and dequeue() the vertex 6. The topological sorted order is 123546 Ve Indegree 1 2 3 4 5 6 1) 0 enque() 3 4 6 Bewet DPP sp spate Python code for Topological ordering of DAG from collections import defaultdict class Graph: def __init__(selfn): self.graph = defaultdict(list) self.N def addEdge(self,m,n): self.graph{m].append(n) def sortUtil(self,n, visited,stack): visited[n] = True for element in self.graph{n): Poy Data Structures Design if visited{element] == False: self.sortUtil(element,visited,stack) stack.insert(0,n) def topologicalSort(self): visited = [False]*selfN stack =[] for element in range(self.N): if visited[element] == False: self.sortUtil‘element,visited,stack) print(stack) graph = Graph(5) graph.addEdge(0,1); graph.addEdge(0,3); graph.addEdge(1,2); graph.addEdge(2,3); graph.addEdge(2,4); graph.addEdge(3,4); print(‘“The Topological Sort Of The Graph Is: “) graph.topologicalSort() OUTPUT The Topological Sort Of The Graph Is: (0, 1,2, 3, 4] Graph Structures 5.21 5.5.2 Applications of Topological Ordering + Topological sort can be used to quickly find the shortest paths from the weighted directed acyclic graph. ° It is used to check whether there exists a cycle in the graph or not ¢ Topological sort is useful to find the deadlock condition in an Operating system ¢ Topological sort is very useful to find sentence ordering in very fewer efforts ¢ __ Itis used in manufacturing workflows or data serialization in an application It is used for ordering the cell evaluation while recomputing formula values in an excel sheet or spreadsheet. 5.6 MINIMUM SPANNING TREE(MST) A tree is a graph, which is always connected and does not contain any cycle. If we are given an undirected and connected graph, a spanning tree is a tree that contains all the vertices(V) of the graph and IV|-1 edges. For a given graph, we can have multiple spanning trees. an i. eae) Trees Sal @ (A) (A) o> © © © © Fig. 5.11 Spanning Tree If there are n vertices and e edges in the graph, then any spanning tree Corresponding to that graph contains n vertices and n-1 edges. 5.6.1 Properties of spanning trees . A connected and undirected graph can have more than one spanning tree. * The spanning tree is free of loops, ic., it is acyclic. a 5.22 Data Structures Design ~ Removing any one of the edges will make the graph disconnected, « Adding an extra edge to the spanning tree will create a loop in the graph. 5.6.2 Minimum Spanning Tree(MST) In a weighted graph, the MST is a spanning tree with minimum weight than all other spanning trees of that graph. Refer to the image below for better understanding, where the edges marked in bold represent the edges of the spanning tree 1 1 1 4 2 4| 2 4 2 5 5 5 Undirected ‘Spanning Minimum Spanning graph tree tree Cost=11(=4+5+2) Cost=7(=4+1+2) Fig 5.12 Minimum Spanning Tree 1. Kruskal’s Algorithm: This algorithm is used to find MST for the given graph. It builds the spanning tree by adding edges one at a time. We start by picking the edge with minimum weight, adding that edge into the MST, and increasing the count of edges in the spanning tree by one. Now, we will be picking the minimum weighted edge by excluding the already chosen ones and correspondingly increasing the count. While choosing the edge, we will also make sure that the graph remains acyclic after including the same. This process will continue until the count of edges in the MST reaches n-- Ultimately, the graph obtained will be MST. Example Graph Structures This is the final MST obtained using Kruskal’s algorithm. It can be checked manually that the final graph is the MST for the given graph, Cycle Detection While inserting a new edge in the MST, we have to check if introducing that edge makes the MST cyclic or not. If not, then we can include that edge, otherwise not.Now, let’s figure out a way to detect the cycle in a graph. The following are the possible cases: * By including an edge between nodes A and B, if both nodes A and B are not Present in the graph, then it is safe to include that edge as including it, will not bring a cycle to the graph. * Out of two vertices, if any one of them has not been visited (or not present in the MST), then that vertex can also be included in the MST, If both the vertices are already present in the graph, they can introduce a cycle in the MST. It means we can’t use this method to detect the presence of the cycle. 5.23 5.24 Data Structures Design Union-Find Algorithm: we will check if the two vertices of the er words, we are checking whether then it is safe to add that edge Before adding any edge to the graph, edge lie in the same component of MST or not, in oth the addition of an edge will lead to a cycle or not. If not, to the MST. Following the steps of the algorithm: ‘We will assume that initially, the total number of disjoint sets is equal to the . number of vertices in the graph starting from Oton-l. «We will maintain a parent array specifying the parent vertex of each of the vertex of the graph. Initially, as each vertex belongs to a different disjoint set (connected component), hence each vertex will be its parent. Now, before inserting any edge into the MST, we will check the parent of the vertices. If their parent vertices are equal, they belong to the same connected component; hence it is unsafe to add that edge. Otherwise, we can add that edge into the MST, and simultaneously update the parent array so that they belong to the same component. O—) © eee) Q Q20Q0Q9 mm) © © © @) 5 Find: 0 belongs to subset 0 and 1 belongs to subset 1 so they are in different subsets. Graph Structures 5.25 Parent of 1, Updated set is {0,1},0 is the set representative O—D @ B © O OQ QO ©O © Union: Make 0 as the since 0 is parent for itself. Subsets. (0) © © Edge 0-2 Find: 0 belongs to subset 0 and 2 belongs to subset 2 so they are in different subsets. Union: Make 0 as the parent of 2, Updated set is {0,1,2},0 is the set representative since 0 is parent for itself. Initially all parent pointers are pointing to self means only one element in each Subset Data Structures Design $26 @—_®) @ 2) @ Subsets (0) ® Q @ @ Edge 1-3 Find: | belongs to subset 0 and 3 belongs to subset 3 so they are in different subsets. Union: Make 1 as the parent of 3,Updated set is {0,1,2,3},0 is the set representative since 0 is parent for itself. Graph Structures 5.27 Edge 3-4 Find: 3 belongs to subset 0 and 4 belongs to subset 4 so they are in different subsets. Union: Make 3 as the parent of 4,Updated set is {0,1,2,3,4). Python code for Kruskal Algorithm # Kruskal’s algorithm in Python class Graph: def __ init__(self, vertices); self.V = vertices self.graph = [] def add_edge(self, u, v, w): self.graph.append({u, v, w]) # Search function def find(self, parent, i): if parent[i] == i: return i return self.find(parent, parent{i) def apply_union(self, parent, rank, x, y): xroot = self.find(parent, x) yroot = self.find(parent, y) if rank[xroot] < rank[yroot]: parent[xroot] = yroot elif rank[xroot] > rank[yroot]: parent[yroot] = xroot else: parent[yroot] = xroot rank[xroot] += 1 # Applying Kruskal algorithm def kruskal_algo(self): 5.28 Data Structures p, result = [] i,e=0,0 self.graph parent = [] rank = [] for node in range(self.V): parent.append(node) rank.append(0) while e < self.V - I: u, v, w= self.graphfi] i=itl x = self.find(parent, u) y = self.find(parent, v) ifx!=y: e=ertl result.append((u, v, w]) self.apply_union(parent, rank, x, ¥) for u, v, weight in result: print(“Yed - Yd: %d” % (u, v, weight)) = sorted(self.graph, key=lambda item: item[2]) g = Graph(6) g.add_edge(0, 1, 4) g.add_edge(0, 2, 4) g.add_edge(1, 2, 2) g.add_edge(1, 0, 4) g.add_edge(2, 0, 4) g.add_edge(2, 1, 2) g.add_edge(2, 3, 3) g.add_edge(2, 5, 2) g.add_edge(2, 4, 4) g.add_edge(3, 2, 3) g.add_edge(3, 4, 3) g.add_edge(4, 2, 4) g.add_edge(4, 3, 3) g.add_edge(5, 2,2) g.add_edge(5, 4, 3) g-kruskal_algo() 5.23 OUTPUT 1-2:2 2-5:2 2-3:3 3-4:3 0-1:4 Time Complexity of Kruskal’s Algorithm: ¢ The total number of vertices is n, and the total number of edges is E. Take input in the array of size E. Sort the input array based on edge-weight. This step has the time complexity of O(E log(E)). Pick (n-1) edges and put them in MST one-by- edge to the MST, we checked for cycle detection, in the worst-case time compl discussed earlier. -one. Also, before adding the detection for each edge. For cycle lexity of E edges will be O(E.n), 2 Hence, the total time complexi ty of Kruskal’s algorithm becomes O(E log{E) +n.E). This time complexity is bad and needs to be improved. The basic idea in these algorithms is that we will be avoiding the formation of skewed-tree structure, which reduces the time complexity for each vecex to O(log(E)). Prim’s Algorithm This algorithm is used to find MST for a given undirected-aeighied govt (which can also be achieved using Kruskal’s Algorithm) In this ai the MST is built by adding one edge at a time. In tbe beginning. the spanning tree consists of only one vertex, which is chosen arbitrarily from the set of all vertices of the graph. Then the minimum weighted edge, outgoing from this vertex. is selected and simultaneously inserted into the MST. Now. the tree contains two edges. Further, we will be selecting the edze with the minimum weight such that one end is already present there in the MST and the other one from the unselected set of vertices. This process is repeated until we have inserted a total of (n-1) edges im the MST. 5.30 Example: Step 1: Start with a Weighted Graph Step 2: Choose a vertex o Step 3: Choose the shortest edge from this vertex and add it. | Step 4: Choose the nearest vertex not yet in the solution. 5Ong Step 5: Choose the nearest edge not yet in the solution, if there are multiple choices, choose one at random. Step 6: Repeat until you have spanning Tree. Graph Structures 5.31 Implementation: We are considering the starting vertex to be 0 witha Parent equal to -1, and weight is equal to 0 (The weight of the edge from vertex 0 to vertex 0 itself). The parent of all other vertices is assumed to be NIL, and the weight will be equal to infinity, which means that the vertex has not been visited yet, We will mark the vertex 0 as visited and the rest as unvisited. If we add any vertex to the MST, then that vertex will be shifted from the unvisited section to the visited section.Now, we will update the weights of direct neighbors of vertex 0 with the edge weights as these are smaller than infinity. We will also update the parent of these vertices and assign them 0 as we reached these vertices from vertex 0, This way, we will keep updating the weights and parents, according to the edge, which has the minimum weight connected to the respective vertex. Python Code for Prim’s Algorithm # Prim’s Algorithm in Python INF = 9999999 # number of vertices in graph N=5 #creating graph by adjacency matrix method G = [(0, 19, 5, 0, 0), [19, 0, 5, 9, 2), (5,5, 0, 1, 6], (0,9, 1, 0, 1), (0, 2, 6, 1, 0]] selected_node = [0, 0, 0, 0, 0] no_edge = 0 Data Structures Deg, selected_node[0] = True # printing for edge and weight print(“Edge : Weight\n”) while (no_edge < N - 1): minimum = INF a=0 b=0 for m in range(N): if selected_node[m]: for n in range(N): if (not selected_node{n]) and G[m][n]): # not in selected and there is an edge if minimum > G[m][n]: minimum = G[m][n] a=m b=n print(str(a) + “-” + str(b) + “:” + str(G[a][b])) selected_node[b] = True no_edge += 1 Output Edge : Weight 0-2:5 2-3:1 3-4:1 4-1:2 Time Complexity of Prim’s Algorithm: Here, n is the number of vertices, and E is the number of edges. . eighted vertex is O(n) for The time complexity for finding the minimum wé . each iteration. So for (n-1) edges, it becomes O(n2). Graph Structures $33 Similarly, for exploring the neighbor vertices, the time taken is O(n2). Itmeans the time complexity of Prim’s algorithm is O(n2). We can improve this in the following ways: For exploring neighbors, we are required to visit every vertex because of the adjacency matrix. We can improve this by using an adjacency list instead of a matrix, Now, the second important thing is the time taken to find the minimum weight vertex, which is also taking a time of O(n2). Here, out of the available list, we are trying to figure out the one with minimum weight. This can be optimally achieved using a priority queue where the priority will be taken as weights of the vertices, This will take O(log(n)) time complexity to remove a vertex from the priority queue. These optimizations can lead us to the time complexity of O((n+E)log(n)), which is much better than the earlier one. 5.7 ALGORITHM: MINIMUM COST PATH This algorithm is used to find the shortest distar weighted non-cyclic graph, ince between any two vertices ina Example: We want to calculate the shortest path between the si vertices in the following graph. source vertex C and all other While executing the algorithm, we will mark every node with its minimum distance to the selected node, which is C in our case. Obviously, for node C itself, this distance will be 0, and for the rest of the nodes, we will assume that the distance is infinity, which also denotes that these vertices have not been visited till now. 334 Data Structures Desig © Now, we will check for the neighbors of the current node, which are A, and D. Now, we will add the minimum cost of the current node to the weigh of the edge connecting the current node and the particular neighbor node © Forexample, for node B, its weight will become minimum(infinity, 0+7) 7. This same process is repeated for other neighbor nodes. Now, as we have updated the distance of all the neighbour nodes of the current node, we will mark the current node as visited. 2 «After this, we will be selecting the minimum weighted node among the remaining vertices. In this case, it is node A. Take this node as the current node. Now, we will repeat the above steps for the rest of the vertices. The pictorial representation of the same is shown below: Graph Structures 535 e Finally, we will get the graph as follows:The distances finally marked at each node are minimum from node C. 5.36 Data Structures Desi ———= Time Complexity of Dijkstra’s algorithm: ‘The time complexity is also the same as that of Prim’s algorithm, i.c., (7?) —_ This can be reduced by using the same approaches as discussed in Prim’s algorithm ————= content. Graph Structures 5.37 TWO MARKS QUESTION AND ANSWERS, 1. Define Graph. A Graph is defined as G = (V, E) where V is the set of vertices (nodes) and F is the set of edges(arcs) connecting the vertices. An edge is represented as u pair of vertices (u,v). 2. | What are Directed graphs? Ifa pair of vertices for any edge is ordered, then that graph is called as or directed graph. 3. Define Path. A path in a graph is a sequence of vertices w1,w2w.3.wN such that Vit | belongs to E for a value 1<=I<=N. The length of such a path is the nuraber or edges on the path, which is equal to n-1. 4. Define Cycle. A cycle is a path in which the first and last vertices are the same. 5. Define Acyclic graph. A graph with no cycles is called Acyclic graph. A directed graph with no Edges is called as a directed Acyclic graph (or) DAG, DAGS are used for Compiler Optimization process. 6. Define Connected graph. A graph is connected when there is a path between every pair of vertices, In a connected graph, there are no unreachable vertices. A connected graph has a path between each pair of distinct vertices. 5.38 Data Structures 7. What are the conditions for a graph to become a tree? A graph is a tree if it has two properties. 1. Ifitis a connected graph. 2. There should not be any cycles in the graph. 8. Give the types of representation of graphs. 1. Adjacency matrix 2. Adjacency linked list 9. Define Adjacency Matrix Adjacency matrix consists of a n*n matrix where n is the no. of vertices presem==—= In the graph, this consists of values either 0 or 1. 10. List out the ways in which a graph is represented. Adjacency matrix representation, Linked list representation. 11. What do you mean by graph traversal? Graph traversal (also known as graph search) refers to the process of visti == (checking and/or updating) each vertex ina graph. Such traversals are classifi-———= as Breadth First Search (BFS) and Depth First Search (DFS) by the order i which the vertices are visited. Tree traversal is a special case of graph traversa_— 12. What is a tree edge? Traversal from one vertex to the next vertex in a graph is called as a tree edge—— 13. Define Topological sort. Topological sort is defined as an ordering of vertices ina directed acyclic graph_— Such that if there is a path from Vi to Vj, then Vj appears after Vi in the ordering —— 14. What is the running time for topological sort? The running time of the algorithm for topological sort is O( V2).For the algorithm using Queue, the running time is O ( E + V ) if adjacency list are used. 15. What do you mean by indegree and outdegree? A directed graph with vertices labeled (indegree, outdegree). For a vertes te number of head ends adjacent to a vertex is called the indegree of | the vertex “pranching the number of tail ends adjacent to a vertex is its outdegree (called factor” in trees) Graph Structures 5.39 16. Define depth-first traversal in a tree. Depth first works by selecting one vertex V of G as a start vertex; V is marked visited. Then each unvisited vertex adjacent to V is searched in turn using depth first search recursively. This process continues until a vertex with no adjacent unvisited vertices is encountered. 17. List the two important key points of DFS + _ Ifpath exists from one node to another, walk across the edge ~ exploring the edge. ¢ — Ifpath does not exist from one specific node to any other node, return to the Previous node where we have been before — backtracking 18. State the difference between BFS and DFS. 19. 21. DFS BFS Backtracking is possible froma dead | » Backtracking is not possible end Vertices are processed in LIFO order _| » Vertices explored are organized in FIFO queue Search is done in one particular direction at a time until dead end is reached Vertices at the same level are searched simultaneously Give any two applications of DFS and BFS. DFS: Detecting cycle in graph, Topological sorting, Path finding BFS: GPS Navigation System, Broadcasting in Network, Minimum spanning tree, What is a minimum spanning tree? A minimum spanning tree of an undirected graph G is a tree formed from Graph edges.that connect all the vertices of G at lowest total cost. What is a single souce shortest path problem? Given as an input,a weighted graph,G= and a distinguished vertex ‘S’ as the source vertex.Single source shortest path problem finds the shortest weighted path from s to every other vertex in G, g 2 é 24, 25. 26. ee N Data Structures Design in about L ighted shortest path. Single source shovest path finds the shortest path from the source lo each and sent in a unweighted graph.Here uo cost is associated with the cdges connecting the vertices.Always unit cost is associated with each edge. every Verlex pi Explain about Weighted shortest path Single source shortest path finds the shortest path from the source to each and Every vertex present In a weighted graph.In a weighted graph soine cost is always Associated with the edges connecting the vertices. What are the methods to solve minimum spanning tree? a) Prim’s algorithm 0) Kruskal’s algorithm Explain briefly about Prim’s algorithm Prim’s algorithm creates the spanning tree in various stages. At each stage,a node is picked as the root and an edge is added and thus the associated vertex along with it. Define a depth first spanning tree. The tree that is formulated by depth first search on a graph is called as depth first spanning tree. The depth first spanning tree consists of tree edges and back edges. REVIEW QUESTIONS Explain the various types of graph representations. Explain the various types of Graph traversals with neat algorithms. Explain the concept of Topological Sort algorithm with example. Explain Dijkstra Algorithms for finding the shortest path in network with an example. Define spanning tree. Explain Prims algorithm to find minimum spanning tree in the connected graph with an example. Describe and justify Kruskal’s algorithm for finding minimum spanning tree for undirected 3raph.

You might also like