PRACTICAL 8 (Kruskal's)

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

Practical No :- 8

OBJECTIVE: Introduction , Design and Implementation of Minimum


Spanning Tree using Kruskal’s Algorithm

INTRODUCTION :

In Kruskal’s algorithm, sort all edges of the given graph in increasing order. Then it keeps on
adding new edges and nodes in the MST if the newly added edge does not form a cycle. It
picks the minimum weighted edge at first and the maximum weighted edge at last. Thus we
can say that it makes a locally optimal choice in each step in order to find the optimal
solution.

EXAMPLE :

Kruskal's algorithm is a minimum spanning tree algorithm that takes a graph as input and
finds the subset of the edges of that graph which
form a tree that includes every vertex . has the minimum sum of weights among all the trees
that can be formed from the graph

ALGORITHM :

● Step 1: Sort all edges in increasing order of their edge weights.


● Step 2: Pick the smallest edge.
● Step 3: Check if the new edge creates a cycle or loop in a spanning tree.
● Step 4: If it doesn’t form the cycle, then include that edge in MST. Otherwise, discard
it.
● Step 5: Repeat from step 2 until it includes |V| - 1 edges in MST.

CODE :

class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = []
def addEdge(self, u, v, w):
self.graph.append([u, v, w])
def find(self, parent, i):
if parent[i] != i:
parent[i] = self.find(parent, parent[i])
return parent[i]
def union(self, parent, rank, x, y):
if rank[x] < rank[y]:
parent[x] = y
elif rank[x] > rank[y]:
parent[y] = x
else:
parent[y] = x
rank[x] += 1
def KruskalMST(self):
result = []
i=0
e=0
self.graph = sorted(self.graph,
key=lambda item: item[2])
parent = []
rank = []
for node in range(self.V):
parent.append(node)
rank.append(0)
while e < self.V - 1:
u, v, w = self.graph[i]
i=i+1
x = self.find(parent, u)
y = self.find(parent, v)
if x != y:
e=e+1
result.append([u, v, w])
self.union(parent, rank, x, y)
minimumCost = 0
print("Edges in the constructed MST")
for u, v, weight in result:
minimumCost += weight
print("%d -- %d == %d" % (u, v, weight))
print("Minimum Spanning Tree", minimumCost)
if __name__ == '__main__':
g = Graph(4)
g.addEdge(0, 1, 10)
g.addEdge(0, 2, 6)
g.addEdge(0, 3, 5)
g.addEdge(1, 3, 15)
g.addEdge(2, 3, 4)
g.KruskalMST()

OUTPUT :

You might also like