0% found this document useful (0 votes)
31 views40 pages

DSD Lab Manual

Uploaded by

s.shanmugapriya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views40 pages

DSD Lab Manual

Uploaded by

s.shanmugapriya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 40

EX.NO.

9A IMPLEMENTATION OF TREE REPRESENTATION AND TRAVERSAL


ALGORITHM - INORDER

Aim:
To write a Python program for inorder traverse to search element from binary tree.

Algorithm:
1. Create a binary tree.

2. Initially all the left and right vertex are None, then declare the values using
insert() function.

3. If data>right element place the element in right.

4. If data<left element place the element in left.

5. Print the tree.

6. Traverse the left subtree by recursively calling the in-order function.

7. Visit the root node value.

8. Traverse the right subtree by recursively calling the in-order function.


Program:
class Node:

def__init__(self, data):

self.left = None

self.right = None

self.data = data

# Insert Node

def insert(self, data):

if self.data:

if data<self.data:

if self.left is None:

self.left = Node(data)

else:

self.left.insert(data)

elif data>self.data:

if self.right is None:

self.right = Node(data)

else:

self.right.insert(data)

else:

self.data = data

# Print the Tree

def PrintTree(self):

if self.left:

self.left.PrintTree()
print(self.data)

if self.right:

self.right.PrintTree()

# Inorder traversal

# Left -> Root -> Right

def inorderTraversal(self, root):

res = []

if root:

res = self.inorderTraversal(root.left)

res.append(root.data)

res = res + self.inorderTraversal(root.right)

return res

root = Node(27)

root.insert(14)

root.insert(35)

root.insert(10)

root.insert(19)

root.insert(31)

root.insert(42)

print(root.inorderTraversal(root))

Output:

[10, 14, 19, 27, 31, 35, 42]


EX.NO. 9B IMPLEMENTATION OF TREE REPRESENTATION AND TRAVERSAL
ALGORITHM – PREORDER

Aim:
To write a Python program for preorder traverse to search element from binary tree.

Algorithm:

1. Create a binary tree.

2. Initially all the left and right vertex are None, then declare the values using
insert() function.

3. If data>right element place the element in right.

4. If data<left element place the element in left.

5. Print the tree.

6. Visit the root node value.

7. Traverse the left subtree by recursively calling the in-order function.

8. Traverse the right subtree by recursively calling the in-order function.


Program:

class Node:

def__init__(self, data):

self.left = None

self.right = None

self.data = data

# Insert Node

def insert(self, data):

if self.data:

if data<self.data:

if self.left is None:

self.left = Node(data)

else:

self.left.insert(data)

elif data>self.data:

if self.right is None:

self.right = Node(data)

else:

self.right.insert(data)

else:

self.data = data

# Print the Tree

def PrintTree(self):

if self.left:

self.left.PrintTree()
print(self.data)

if self.right:

self.right.PrintTree()

# Preorder traversal

# Root -> Left -> Right

def PreorderTraversal(self, root):

res = []

if root:

res.append(root.data)

res = self.PreorderTraversal(root.left)

res = res + self.PreorderTraversal(root.right)

return res

root = Node(27)

root.insert(14)

root.insert(35)

root.insert(10)

root.insert(19)

root.insert(31)

root.insert(42)

print(root.PreorderTraversal(root))

Output:

[27, 14, 10, 19, 35, 31, 42]


EX.NO. 9C IMPLEMENTATION OF TREE REPRESENTATION AND TRAVERSAL
ALGORITHM – POSTORDER

Aim:
To write a Python program for postorder traverse to search element from binary tree.

Algorithm:

1. Create a binary tree.

2. Initially all the left and right vertex are None, then declare the values using
insert() function.

3. If data>right element place the element in right.

4. If data<left element place the element in left.

5. Print the tree.

6. Traverse the left subtree by recursively calling the in-order function.

7. Traverse the right subtree by recursively calling the in-order function.

8. Visit the root node value.


Program:

class Node:

def__init__(self, data):

self.left = None

self.right = None

self.data = data

# Insert Node

def insert(self, data):

if self.data:

if data<self.data:

if self.left is None:

self.left = Node(data)

else:

self.left.insert(data)

elif data>self.data:

if self.right is None:

self.right = Node(data)

else:

self.right.insert(data)

else:

self.data = data

# Print the Tree

def PrintTree(self):

if self.left:
self.left.PrintTree()

print(self.data)

if self.right:

self.right.PrintTree()

# Postorder traversal

# Left -> Right -> Root

def PostorderTraversal(self, root):

res = []

if root:

res = self.PostorderTraversal(root.left)

res = res + self.PostorderTraversal(root.right)

res.append(root.data)

return res

root = Node(27)

root.insert(14)

root.insert(35)

root.insert(10)

root.insert(19)

root.insert(31)

root.insert(42)

print(root.PostorderTraversal(root))

Output:

[10, 19, 14, 31, 42, 35, 27]


EX.NO. 10A IMPLEMENTATION OF BINARY SEARCH TREE – INSERT

Aim:

To write a Python program to insert element into binary tree and display inorder vertical
order.

Algorithm:

Program:

class Node:

def __init__(self, key):

self.left = None

self.right = None

self.val = key

def insert (root, key):

if root is None:

return Node (key)


else:

if root.val == key:

return root

elif root.val < key:

root.right = insert (root .right, key)

else:

root.left = insert (root.left, key)

return root

def inorder(root):

if root:
inorder(root.left)

print(root.val)
inorder(root.right)

# Driver program to test the above functions

# Let us create the following BST

# 50

#/

# 30 70

#/\/\

# 20 40 60 80

r = Node (50)

r = insert (r,30)

r = insert (r,20)

r = insert (r,40)

r = insert (r,70)

r = insert (r,60)

r = insert (r,80)

#Print inorder traversal of the BST

inorder (r)

Output:

20

30

40

50

60

70

80
EX.NO.10B IMPLEMENTATION OF BINARY SEARCH TREE - SEARCH

Aim:

To Write a Python program to search element from binary tree.

Algorithm:

1. Read the search element from the user.

2. Compare the search element with the value of root node in the tree.

3. If both are matched, then display "Given node is found!!!" and terminate the
function.

4. If both are not matched, then check whether search element is smaller or larger
than that node value.

5. If search element is smaller, then continue the search process in left subtree.

6. If search element is larger, then continue the search process in right subtree.

7. Repeat the same until we find the exact element or until the search element is
compared with the leaf node.

8. If we reach to the node having the value equal to the search value then display
"Element is found" and terminate the function.
Program:

class Node:

def __init__(self, data):

# Assign data to the new node, set left and right children to None

self.data = data

self.left = None

self.right = None

class SearchBinaryTree:

def __init__(self):

# Represent the root of binary tree

self.root = None

self.flag = False

def searchNode(self, temp, value):

# Check whether tree is empty

if (self.root == None):

print (“Tree is empty”)

else:

if (temp.data == value):

self. flag = True

return

# Search in left subtree

if (self.flag == False and temp.left ! = None):

self.searchNode(temp.left,value)

# Search in right subtree

if (self.flag == False and temp.right!= None):


self.searchNode(temp.right,value)

bt = SearchBinaryTree()

# Add nodes to the binary tree

bt.root = Node (1)

bt.root.left = Node (2)

bt.root.right= Node (3)

bt.root.left.left = Node (4)

bt.root.right.left = Node (5)

bt.root.right.right = Node (6)

print (“Search for node 5 in the binary tree”)

bt.searchNode(bt.root, 5)

if (bt.flag):

print (“Element is present in the binary tree”)

else:

print (“Element is not present in the binary tree”)

Output:

Search for node 5 in the binary tree

Element is present in the binary tree


EX.NO. 11A IMPLEMENTATION OF MIN HEAP

Aim:
To write a python program to find min heap.

Algorithm:

Program:

Class MinHeap:
def __init__(self, maxsize):
self.maxsize = maxsize
self.size = 0
self.Heap = [0]*(self.maxsize + 1)
self.Heap[0] = -1 * sys.maxsize
self.FRONT = 1

# Function to return the position of parent for the node currently at pos
def parent (self, pos):
return pos // 2
# Function to return the position of the left child for the node currently at pos
def leftChild (self, pos):
return 2* pos
# Function to return the position of the right child for the node currently at pos
def rightChild (self, pos):
return (2 * pos) + 1
# Function that returns true if the passed node is a leaf node
def isLeaf (self,pos):
return pos * 2 > self.size
# Function to swap two nodes of the heap
def swap (self, fpos, spos):
self.Heap[fpos], self.Heap[spos] = self.Heap[spos], self.Heap[fpos]
# Function to heapify the node at pos
def minHeapify(self, pos):
# if the node is a non-leaf node and greater than any of its child
if not self.isLeaf(pos):
if (self.Heap[pos] > self.Heap[self.leftChild(pos)] or
self.Heap[pos] > self.Heap[self.rightChild(pos)]):
# Swap with the left child and heapify the left child
if self.Heap[self.leftChild(pos)] < self.Heap[self.rightChild(pos)]:

self.swap(pos, self.leftChild(pos))

self.minHeapify(self.leftChild(pos))

# Swap with the right child and heapify the right child

else:

self.swap(pos, self.rightChild(pos))

self.minHeapify(self.rightChild(pos)

# Function to insert a node into the heap

def insert(self, element):

if self.size >= self.maxsize:

return

self.size+=1

self.Heap[self.size] = element

current=self.size

while self.Heap[current] < self.Heap[self.parent(current)]:

self.swap(current, self.parent(current))
current=self.parent(current)

# Function to print the contents of the heap

def Print(self):

for i in range(1,(self.size // 2)+1):

print(“ PARENT: “+ str(self.Heap[i])+ “ LEFT CHILD : “+

str(self.Heap[2 * i])+” RIGHT CHILD : “+ str(self.Heap[2 * i + 1]))

# Function to build the min heap using the minHeapify function

def minheap(self):

for pos in range(self.size // 2, 0, -1):

self.minHeapify(pos)

# Function to remove and return the minimum element from the heap

def remove(self):

popped = self.Heap[self.FRONT]

self.Heap[self.FRONT] = self.Heap[self.size]

self.size -= 1

self.minHeapify(self.FRONT)

return popped

# Driver Code

if __name__ == “__main__”:

print(‘The minheap is’)

minheap= MinHeap(15)

minHeap.insert(5)

minHeap.insert(3)

minHeap.insert(17)

minHeap.insert(10)
minHeap.insert(84)

minHeap.insert(19)

minHeap.insert(6)

minHeap.insert(22)

minHeap.insert(9)

minheap.minHeap()

minheap.Print()

print(“The Min val is “ + str(minJHeap.remove()))

Output:

The minHeap is

PARENT : 3 LEFT CHILD : 5 RIGHT CHILD : 6

PARENT : 5 LEFT CHILD : 9 RIGHT CHILD : 84

PARENT : 6 LEFT CHILD : 19 RIGHT CHILD : 17

PARENT : 9 LEFT CHILD : 22 RIGHT CHILD : 10

The Min val is 3


EX.NO. 11B IMPLEMENTATION OF MAX HEAP

Aim:
To write a python program to find max heap.

Algorithm:

Program:

Class MaxHeap:
def __init__(self, maxsize):
self.maxsize = maxsize
self.size = 0
self.Heap = [0]*(self.maxsize + 1)
self.Heap[0] = sys.maxsize
self.FRONT = 1

# Function to return the position of parent for the node currently at pos
def parent (self, pos):
return pos // 2
# Function to return the position of the left child for the node currently at pos
def leftChild (self, pos):
return 2* pos
# Function to return the position of the right child for the node currently at pos
def rightChild (self, pos):
return (2 * pos) + 1
# Function that returns true if the passed node is a leaf node
def isLeaf (self, pos):
if pos >= (self.size // 2) and pos <= self.size:
return True
return False
# Function to swap two nodes of the heap
def swap (self, fpos, spos):
self.Heap[fpos], self.Heap[spos] = (self.Heap[spos], self.Heap[fpos])
# Function to heapify the node at pos
def maxHeapify(self, pos):
# if the node is a non-leaf node and smaller than any of its child
if not self.isLeaf(pos):
if (self.Heap[pos] < self.Heap[self.leftChild(pos)] or
self.Heap[pos] < self.Heap[self.rightChild(pos)]):
# Swap with the left child and heapify the left child
if self.Heap[self.leftChild(pos)] > self.Heap[self.rightChild(pos)]:

self.swap(pos, self.leftChild(pos))

self.maxHeapify(self.leftChild(pos))

# Swap with the right child and heapify the right child

else:

self.swap(pos, self.rightChild(pos))

self.maxHeapify(self.rightChild(pos)

# Function to insert a node into the heap

def insert(self, element):

if self.size >= self.maxsize:

return

self.size+=1

self.Heap[self.size] = element

current=self.size

while self.Heap[current] > self.Heap[self.parent(current)]:

self.swap(current, self.parent(current))
current=self.parent(current)

# Function to print the contents of the heap

def Print(self):

for i in range(1,(self.size // 2) + 1):

print(“ PARENT: “+ str(self.Heap[i])+ “ LEFT CHILD : “+

str(self.Heap[2 * i])+” RIGHT CHILD : “+ str(self.Heap[2 * i + 1]))

# Function to remove and return the maximum element from the heap

def extractMax(self):

popped = self.Heap[self.FRONT]

self.Heap[self.FRONT] = self.Heap[self.size]

self.size -= 1

self.maxHeapify(self.FRONT)

return popped

# Driver Code

if __name__ == “__main__”:

print(‘The maxheap is’)

minheap= MaxHeap(15)

maxHeap.insert(5)

maxHeap.insert(3)

maxHeap.insert(17)

maxHeap.insert(10)

maxHeap.insert(84)

maxHeap.insert(19)

maxHeap.insert(6)

maxHeap.insert(22)
maxHeap.insert(9)

minheap.Print()

print(“The Max val is “ + str(maxJHeap.extractMax()))

Output:

The maxHeap is

PARENT : 84 LEFT CHILD : 22 RIGHT CHILD : 19

PARENT : 22 LEFT CHILD : 17 RIGHT CHILD : 10

PARENT : 19 LEFT CHILD : 5 RIGHT CHILD : 6

PARENT : 17 LEFT CHILD : 3 RIGHT CHILD : 9

The Max val is 84


EX.NO. 12B GRAPH REPRESENTATION AND TRAVERSAL

Adjacency List representation

Aim:

To write a Python program to represent graph using adjacency list.

Algorithm:

Program:

# Adjacency List representation in Python

class AdjNode:

def __init__(self,value):

self.vertex = value

self.next = None

class Graph:

def__init__(self,num)

self.V = num

self.graph = [None] * self.V

# Add edges

def add_edge(self, s, d):

node = AdjNode(d)

node.next = self.graph[s]

self.graph[s] = node

node = AdjNode(s)

node.next = self.graph[d]

self.graph[d] = node

# Print the graph


def print_agraph(self):

for i in range(self.V):

print(“Vertex “ + str(i) + “:”, end = “”)

temp = self.graph[i]

while temp:

print(“ -> {} “.format(temp.vertex), end = “”)

temp = temp.next

print(“ \n”)

if __name__ == “ __main__”:

V=5

# Create graph and edges

graph = Graph(V)

graph.add_edge(0,1)

graph.add_edge(0,2)

graph.add_edge(0,3)

graph.add_edge(1,2)

graph.print_agraph()

Output:

Vertex 0: -> 3 -> 2 -> 1

Vertex 1: -> 2 -> 0

Vertex 0: -> 1 -> 0

Vertex 4:
Ex. No. 12C DEPTH FIRST TRAVERSAL

Aim:

To Write a Python program to traverse a graph using DFS.

Algorithm:

Program:

# Python3 program to print DFS traversal from a given graph

from collections import defaultdict

# This class represents a directed graph using adjacency list representation

class Graph:

# Constructor

def __init__ (self):

# default dictionary to store graph

self.graph = defaultdict(list)

# A function to add an edge to graph

def addEdge(self, u, v):

self.graph[u].append(v)

# A function used by DFS

def DFSUtil(self, v, visited):

# Mark the current node as visited and print it

visited.add(v)

print(v, end = ‘ ‘)

# Recur for all the vertices adjacent to this vertex

for neighbour in self.graph[v]:

if neighbour not in visited:


self. DFSUtil(neighbour, visited)

# The function to do DFS traversal. It uses recursive DFSUtil()

def DFS(self,v):

# Create a set to store visited vertices

visited = set()

# Call the recursive helper function to print DFS traversal

Self.DFSUtil(v, visited)

# Driver code

# Create a graph given in the above diagram

g = Graph()

g.addEdge(0,1)

g.addEdge(0,2)

g.addEdge(1,2)

g.addEdge(2,0)

g.addEdge(2,3)

g.addEdge(3,3)

print(“Following is DFS from (starting from vertes 2)”)

g.DFS(2)

Output:
EX. NO. 12D BREADTH FIRST TRAVERSAL

Aim:

To write a Python program to traverse a graph using BFS.

Algorithm:

Program:

graph = {

‘5’ : [‘3’,’7’],

‘3’ : [‘2’, ‘4’],

‘7’ : [‘8’],

‘2’ : [],

‘4’ : [‘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, ‘5’) # function calling

Output:

Following is the Breadth-First Search

5 3 7 2 4 8
EX. NO. 13A SINGLE SOURCE SHORTEST PATH ALGORITHM
Bellman Ford Algorithm

Aim:
To write a Python program for single source shortest path using Bellman Ford Algorithm.

Algorithm:

Program:
def __init__(self, vertices):
self.M = vertices # Total number of vertices in the graph
self.graph = [] # Array of edges
# Add edges
def add_edge(self, a, b,c):
self.graph.append([a, b, c])

# Print the solution


def print solution(self, distance):
print(“Vertex Distance from Source”)
for k in range(self.M):
print(“{0}\t\t{1}”.format(k, distance[k]))
def bellman_ford(self, src):
distance = [float(“Inf”)] * self.M
distance[src] = 0
for_ in range(self.M – 1):
for a, b, c in self.graph:
if distance[a] != float(“Inf”) and distance[a] + c < distance[b]:
distance[b] = distance[a] + c
for a, b, c in self.graph:
if distance[a] != float(“Inf”) and distance[a] + c < distance[b]:
print(“Graph contains negative weight cycle”)
return
self.print_solution(distance)
g = Graph(5)
g.add_edge(0, 1, 2)
g.add_edge(0, 2, 4)
g.add_edge(1, 3, 2)
g.add_edge(2, 4, 3)
g.add_edge(2, 3, 4)
g.add_edge(4, 3, -5)
g.bellman_ford(0)

Output:
Vertex Distance from Source
0 0
1 2
2 4
3 2
4 7
EX. NO. 13B SINGLE SOURCE SHORTEST PATH ALGORITHM
Dijiktra’s Algorithm

Aim:
To write a Python program for single source shortest path using Dijiktra’s Algorithm.

Algorithm:

Program:
# Python program for Dijiktra’s single source shortest path algorithm. The program is for
# adjacency matrix representation of the graph.
class Graph():
def __ init__self(self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)] for row in range(vertices)]
def printSolution(self, dist):
print(“Vertex \t Distance from Source”)
for node in range(self.V):
print(node, “\t\t”, dist[node])
# A utility function to find the vertex with minimum distance value, from the set of
# vertices not yet included in shortest path tree
def minDistance(self, dist, sptSet):
# Initialize minimum distance for next node
min = 1e7
# Search not nearest vertex not in the shortest path tree
for v in range(self.V):
if dist[v] < min and sptSet[v] == False:
min = dist[v]
min_index = v
return min_index
# Function that implements Dijiktra’s single source shortest path algorithm for a graph
# represented using adjacency matrix representation
def dijktra(self, src):
dist = [ 1e7] * self.V
dist[src] = 0
sptSet = [False] * self.V
for cout in range(self.V):
# Pick the minimum distance vertex from the set of vertices not yet processed.
# u is always equal to src in first iteration
u = self.minDistance(dist, sptSet)
# Put the minimum distance vertex in the shortest path tree
sptSet[u] = True
# Update dist value of the adjacent vertices of the picked vertex only if the
# current distance is greater than new distance and the vertex is not in the
# shortest path tree
for v in range(self.V):
if(self.graph[u][v] > 0 and sptSet[v] == False and dist[v] > dist[u] +
self.graph[u][v]);
dist[v] = dist[u] + selfgraph[u][v]
self.printSolution(dist)
# Driver program
g = Graph(9)
g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0],
[4, 0, 8, 0, 0, 0, 0, 11, 0],
[0, 8, 0, 7, 0, 4, 0, 0, 2],
[0, 0, 7, 0, 9, 14, 0, 0, 0],
[0, 0, 0, 9, 0, 10, 0, 0, 0],
[0, 0, 4, 14, 10, 0, 2, 0, 0]
[0, 0, 0, 0, 0, 2, 0, 1, 6]
[8, 11, 0, 0, 0, 0, 1, 0, 7]
[0, 0, 2, 0, 0, 0, 6, 7, 0]
]
g.dijktra(0)

Output:

Vertex Distance from Source


0 0
1 4
2 12
3 19
4 21
5 11
6 9
7 8
8 14
EX. NO. 14A IMPLEMENTATION OF MINIMUM SPANNING TREE
Prim’s algorithm

Aim:
To write a Python program to find minimum spanning tree from a given graph using
Prim’s algorithm.

Algorithm:
Program:
# A Python program for Prim’s Minimum Spanning Tree (MST) algorithm.
# The program is for adjacency matrix representation of the graph.
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]])
# A utility function to find the vertex with minimum distance value, from the set of
# vertices not yet included in shortest path tree
def minKey(self, key, mstSet):
# Initialize min value
min = sys.maxsize
for v in range(self.V)
if key[v] < min and mstSet[v] == False:
min = key[v]
min_index = v
return min_index
# Function to construct and print MST for a graph represented using adjacency matrix
# representation
def printMST(self):
# Key values used to pick minimum weight edge in cut
key = [sys.maxsize] * self.V
parent = [None] * self.V # Array to store constructed MST
# Make key 0 so that this vertex is picked as first vertex
key[0] = 0
mstSet = [False] * self.V

parent[0] = -1 # First node is always the root of


for cout in range(self.V):
# Pick the minimum distance vertex from the set of vertices not yet processed.
# u is always equal to src in first iteration
u = self.minKey(key, mstSet)
# Put the minimum distance vertex in the shortest path tree
mstSet[u] = True

# Update dist value of the adjacent vertices of the picked vertex only if the
# current distance is greater than new distance and the vertex is not in the shortest
# path tree
for v in range(self.V):
# graph[u][v] is non zero only for adjacent vertices of m
# mstSet[v] is False for vertices not yet included in MST
# Update the key only if graph[u][v] is smaller than key[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(5)
g.graph = [ [0, 2, 0, 6, 0],
[2, 0, 3, 8, 5],
[0, 3, 0, 0, 7]
[6, 8, 0, 0, 9],
[0, 5, 7, 9, 0] ]
g.primMST()

Output:
Edge Weight
0–1 2
1–2 3
0–3 6
1–4 5
EX. NO. 14B IMPLEMENTATION OF MINIMUM SPANNING TREE
Kruskal’s algorithm

Aim:
To Write a Python program to find minimum spanning tree from a given graph using
Kruskal algorithm.
Algorithm:
1. Label each vertex
2. List the edges in non-decreasing order of weight.
3. Start with the smallest weighted and beginning growing the minimum weighted
spanning tree from this edge.
4. Add the next available edge that does not form a cycle to the construction of the
minimum weighted spanning tree. If the addition of the next least weighted edge
forms a cycle, do not use it.
5. Continue with step 4 until you have a spanning tree.
6. Stop the program.
Program:
from collections import defaultdict
class Graph:
def __init__(self,vertices):
self.V = vertices # No. of vertices

self.graph = [] # default dictionary to store graph

def addEdge(self, u, v, w):

self.graph.append([u, v, w])

# A utility function to find set of an element i (uses path compression technique)

def find (self, parent, i):

if parent[i] == i:

return i

return self.find(parent,parent[i])

# A function that does union of two sets of x and y (uses union by rank)

def union (self, parent, rank, x, y):

xroot = self.find(parent, x)
yroot = self.find(parent, y)

# Attach smaller rank tree under root of high rank tree (Union by Rank)

if rank[xroot]< rank[yroot]:

parent[xroot] = yroot

elif rank[xroot]> rank[yroot]:

parent[yroot] = xroot

# If ranks are same, then make one as root and increment its rank by one

else:

parent[yroot] = xroot

rank[xroot] += 1

# The main function to construct MST using Kruskal’s algorithm

def KruskalMST(self):

result = [] # This will store the resultant MST

# An index variable, used for sorted edges

i=0;

# An index variable, used for result[]

e=0

# Step 1: Sort all the edges in non-decreasing order of their weight. If we are not

# allowed to change the given graph, we can create a copy of graph

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

u, v, w = self.graph[i]

i = i+1

x = self.find(parent, u)

y = self.find(parent, v)

# If including this edge doesn’t cause cycle, include it in result and increment

# the index of result for next edge

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)

# Driver code

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)

# Function call

g.KruskalMST()
Output:

Edges in the constructed MST

2 -- 3 == 4

0 -- 3 == 5

0 -- 1 == 10

Minimum Spanning Tree 19

You might also like