Answered step by step
Verified Expert Solution
Question
1 Approved Answer
from collections import defaultdict class Graph: # constructing and initilize def __init__(self, vertices): self.V = vertices # num vertices self.graph = [] # creating edge
from collections import defaultdict class Graph: # constructing and initilize def __init__(self, vertices): self.V = vertices # num vertices self.graph = [] # creating edge function def addEdge(self, i, j, w): self.graph.append([i, j, w]) # function to find k elements def find(self, parent, k): if parent[k] == k: return k return self.find(parent, parent[k]) # union function uses set a b by rank def union(self, parent, rank, a, b): aroot = self.find(parent, a) broot = self.find(parent, b) # Attach smaller rank tree under root of high rank tree if rank[aroot] < rank[broot]: parent[aroot] = broot elif rank[aroot] > rank[broot]: parent[broot] = aroot # If ranks are same increment its rank by one else: parent[broot] = aroot rank[aroot] += 1 # The main function for the min spannng tree globally minumim cost edge def minimum_spanning_tree(self): result = [] # This will store the resultant MST k = 0 # An index variable, used for sorted edges e = 0 # An index variable, used for result[] # Sort all the edges in non-decreasing self.graph = sorted(self.graph, key=lambda item: item[2]) parent = [] rank = [] # Create V subsets with single elements for node in range(self.V): parent.append(node) rank.append(0) # Number of edges to be taken is equal to V-1 while e < self.V - 1: # Step 2: Pick the smallest edge and increment # the index for next iteration i, j, w = self.graph[k] k = k + 1 a = self.find(parent, i) b = self.find(parent, j) # If including this edge does't cause cycle, # include it in result and increment the index # of result for next edge if a != b: e = e + 1 result.append([i, j, w]) self.union(parent, rank, a, b) # Else discard the edge # print the contents of result[] to display the built MST print "Following are the edges in the constructed MST" for i, j, weight in result: # print str(i) + " - " + str(j) + " weights " + str(weight) print("%d - %d weights %d" % (i, j, weight)) # Driver code g = Graph(3) g.addEdge(1, 2, 5) g.addEdge(2, 3, 10) g.addEdge(1,3, 9) I have this code and when I start veritices from zero like this it runs fine (0,1,5), (1,2,10) and (0,2, 9). However, when I start it with one (1,2,5), (2,3,10) and (1,3,9). it gives me following error. index out of range. i could not figure it out. help me out.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started