Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys # Library for INT_MAX
- class Graph():
- def __init__(self, vertices):
- self.V = vertices
- self.graph = [[0 for column in range(vertices)]
- for row in range(vertices)]
- # A utility function to print the constructed MST stored in parent[]
- def printMST(self, parent):
- print "Edge \tWeight"
- for i in range(1,self.V):
- print parent[i],"-",i,"\t",self.graph[i][ parent[i] ]
- def minKey(self, key, mstSet):
- min = sys.maxint
- for v in range(self.V):
- if key[v] < min and mstSet[v] == False:
- min = key[v]
- min_index = v
- return min_index
- def primMST(self):
- key = [sys.maxint] * self.V
- parent = [None] * self.V # Array to store constructed MST
- key[0] = 0 # Make key 0 so that this vertex is picked as first vertex
- mstSet = [False] * self.V
- parent[0] = -1 # First node is always the root of
- for cout in range(self.V):
- u = self.minKey(key, mstSet)
- # Put the minimum distance vertex in the shortest path tree
- mstSet[u] = True
- for v in range(self.V):
- if self.graph[u][v] > 0 and mstSet[v] == False and key[v] > self.graph[u][v]:
- key[v] = self.graph[u][v]
- parent[v] = u
- self.printMST(parent)
- g = Graph(10)
- g.graph = [
- [0,4230,4700,4716,4690, 4674, 5070,4880,4280,3880],
- [4230,0,534,682,950, 780, 1110,1190,2700,3100],
- [4700,534,0,190,544, 288, 787,1092,2600,3000],
- [4716,682,190,0,378, 122, 620,926,2436,2830],
- [4690,950,544,378,0, 256, 280,580,2100,2436],
- [4674,780,288,122,256, 0, 500,810,2320,2710],
- [5070,1110,787,620,280, 500, 0,330,1840,2200],
- [4880,1190,1092,926,580, 810, 330,0,1650,1985],
- [4280,2700,2600,2436,2100, 2320, 1840,1650,0,450],
- [3880,3100,3000,2830,2436, 2710, 2200,1985,450,0]
- ]
- g.primMST();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement