TEC - Algorithm Lab
TEC - Algorithm Lab
TEC - Algorithm Lab
IV Semester: CSE
4|Page
LIST OF EXPERIMENTS
b) Compute the transitive closure of a given directed graph using Warshall's algorithm.
5|Page
WEEK-6 MINIMUM COST SPANNING TREE
Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal’s algorithm.
6|Page
WEEK-8 GRAPH TRAVERSALS
a. Print all the nodes reachable from a given starting node in a digraph using BFS method.
7|Page
WEEK-12 ALL PAIRS SHORTEST PATHS
Implement All-Pairs Shortest Paths Problem using Floyd's algorithm.
Reference Books:
1. Levitin A, “Introduction to the Design And Analysis of Algorithms”, Pearson Education, 2008.
2. Goodrich M.T.,R Tomassia, “Algorithm Design foundations Analysis and Internet Examples”, John
Wileyn and Sons, 2006.
3. Base Sara, Allen Van Gelder ,“ Computer Algorithms Introduction to Design and Analysis”,
Pearson, 3rd Edition, 1999.
Web References:
1. http://www.personal.kent.edu/~rmuhamma/Algorithms/algorithm.html
2. http://openclassroom.stanford.edu/MainFolder/CoursePage.php?course=IntroToAlgorithms
3. http://www.facweb.iitkgp.ernet.in/~sourav/daa.html
8|Page
WEEK-1
QUICK SORT
1.1 OBJECTIVE:
Sort a given set of elements using the Quick sort method and determine the time required to sort
the elements. Repeat the experiment for different values of n, the number of elements in the list to
be sorted and plot a graph of the time taken versus n. The elements can be read from a file or can
be generated using the random number generator.
1.2 RESOURCES:
IDLE(python GUI)
QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the given
array around the picked pivot.
There are many different versions of QuickSort that pick pivot in different ways.
1. Always pick first element as pivot.
2. Always pick last element as pivot (implemented below)
3. Pick a random element as pivot.
4. Pick median as pivot.
The key process in QuickSort is partition. Target of partitions is, given an array and an element x
of array as pivot, put x at its correct position in sorted array and put all smaller elements (smaller
than x) before x, and put all greater elements (greater than x) after x.
1.4 PROCEDURE:
1. Create: Open IDLE(python GUI), write a program after that save the program with .c extension.
2. Run Module (F5)
def partition(a,low,high):
pivotvalue=a[low]
up=low+1
down=high
done=False
while not done:
while up<=down and a[up]<=pivotvalue:
up+=1
while down>=up and a[down]>=pivotvalue:
9|Page
down-=1
if down<up:
done=True
else:
temp=a[up]
a[up]=a[down]
a[down]=temp
temp=a[low]
a[low]=a[down]
a[down]=temp
return down
10 | P a g e
WEEK-2
MERGE SORT
2.1 OBJECTIVE:
Implement merge sort algorithm to sort a given set of elements and determine the time required to sort
the elements. Repeat the experiment for different values of n, the number of elements in the list to be
sorted and plot a graph of the time taken versus n. The elements can be read from a file or can be
generated using the random number generator.
2.2 RESOURCES:
IDLE(python GUI)
Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls itself for the
two halves and then merges the two sorted halves.
The merge() function is used for merging two halves. The merge(a, low, mid, high) is key process
that assumes that a[low..mid] and a[mid+1..high] are sorted and merges the two sorted sub-arrays into
one.
2.4 PROCEDURE:
1. Create: Open IDLE(python GUI), write a program after that save the program with .c extension.
2. Run Module(F5)
def m_sort(a):
for i in
range(len(a)):
if i>1:
mid=len(a)//2
l_half=a[:mid]
r_half=a[mid:]
m_sort(l_half)
m_sort(r_half)
i=j=k=0
while i<len(l_half) and j<len(r_half):
if l_half[i]<r_half[j]:
a[k]=l_half[i]
i+=1
else:
a[k]=r_half[j]
j+=1
k+=1
11 | P a g e
while
i<len(l_half):
a[k]=l_half[i]
i+=1
k+=1
while
j<len(r_half):
a[k]=r_half[j]
j+=1
k+=1
print("Enter
elements into list")
a=[int(x) for x in
input().split()]
m_sort(a)
print(a)
12 | P a g e
WEEK-3
WARSHALL’S ALGORITHM
3.1 OBJECTIVE:
1. Obtain the Topological ordering of vertices in a given digraph.
2. Compute the transitive closure of a given directed graph using Warshall's algorithm.
3.2 RESOURCES:
IDLE(python GUI)
Topological ordering
In topological sorting, a temporary stack is used with the name “s”. The node number is not printed
immediately; first iteratively call topological sorting for all its adjacent vertices, then push adjacent
vertex to stack. Finally, print contents of stack. Note that a vertex is pushed to stack only when all of
its adjacent vertices (and their adjacent vertices and so on) are already in stack.
Transitive closure
Given a directed graph, find out if a vertex j is reachable from another vertex i for all vertex pairs (i, j)
in the given graph. Here reachable mean that there is a path from vertex i to j. The reach-ability
matrix is called transitive closure of a graph.
3.4 PROCEDURE:
1. Create: Open IDLE(python GUI), write a program after that save the program with .c extension.
2. Run Module(F5)
Topological ordering
14 | P a g e
WEEK-4
KNAPSACK PROBLEM
4.1 OBJECTIVE:
4.2 RESOURCES:
IDLE(python GUI)
Given some items, pack the knapsack to get the maximum total profit. Each item has some
Weight and some profit. Total weight that we can carry is no more than some fixed number W.
4.4 PROCEDURE:
1. Create: Open IDLE(python GUI), write a program after that save the program with .c extension.
2. Run Module(F5)
16 | P a g e
WEEK-5
5.2 RESOURCES:
IDLE(python GUI)
1) Create a set S that keeps track of vertices included in shortest path tree, i.e., whose minimum
distance from source is calculated and finalized. Initially, this set is empty.
2) Assign a distance value to all vertices in the input graph. Initialize all distance values as
INFINITE.Assign distance value as 0 for the source vertex so that it is picked first.
3) While S doesn’t include all vertices
a) Pick a vertex u which is not there in S and has minimum distance value.
b) Include u to S.
c) Update distance value of all adjacent vertices of u.
To update the distance values, iterate through all adjacent vertices. For every adjacent vertex v, if
sum of distance value of u (from source) and weight of edge u-v, is less than the distance value of v,
then update the distance value of v.
5.4 PROCEDURE:
1. Create: Open IDLE(python GUI), write a program after that save the program with .c extension.
2. Run Module(F5)
def dij(n,v,cost,dist):
flag=[0 for x in range(1,n+2,1)]
for i in range(1,n+1,1):
flag[i]=0
dist[i]=cost[v][i]
17 | P a g e
count=2
while count<=n:
mini=99
for w in range(1,n+1,1):
if (dist[w] < mini and not(flag[w])):
mini=dist[w]
u=w
flag[u]=1
count=count+1
for w in range(1,n+1,1):
if ((dist[u]+cost[u][w]<dist[w]) and not(flag[w])):
dist[w]=dist[u]+cost[u][w]
n=int(input("Enter number of nodes:"))
cost=[[0 for j in range(1,n+2,1)] for i in range(1,n+2,1)]
print("Enter the adjacency matrix:")
for i in range(1,n+1,1):
for j in range(1,n+1,1):
temp=int(input())
cost[i][j]=temp
if cost[i][j]==0:
cost[i][j]=999
v=int(input("Enter the source node:"))
dist=[0 for i in range(1,n+2,1)]
dij(n,v,cost,dist)
print("***********Shortest path*********")
for i in range(1,n+1,1):
if(i!=v):
print(v,"->",i,"cost=",dist[i])
18 | P a g e
5.7 LAB VIVA QUESTIONS:
19 | P a g e
WEEK-6
Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal’s algorithm.
6.2 RESOURCES:
IDLE(python GUI)
6.4 PROCEDURE:
1. Create: Open IDLE(python GUI), write a program after that save the program with .c extension.
2. Compile: Alt + F9
3. Execute: Ctrl + F10
23 | P a g e
WEEK-7
TREE TRAVESRSALS
7.1 OBJECTIVE:
7.2 RESOURCES:
IDLE(python GUI)
Traversal is a process to visit all the nodes of a tree and may print their values too.
Inorder(tree)
1. Traverse the left subtree, i.e., call Inorder(left-subtree)
2. Visit the root.
3. Traverse the right subtree, i.e., call Inorder(right-subtree)
Postorder(tree)
1. Traverse the left subtree, i.e., call Postorder(left-subtree)
2. Traverse the right subtree, i.e., call Postorder(right-subtree)
3. Visit the root.
Preorder(tree)
1. Visit the root.
2. Traverse the left subtree, i.e., call Preorder(left-subtree)
3. Traverse the right subtree, i.e., call Preorder(right-subtree)
7.4 PROCEDURE:
1. Create: Open IDLE(python GUI), write a program after that save the program with .c extension.
2. Run Module(F5)
def minValueNode(node):
current = node
while(current.left is not None):
current = current.l
return current
def deleteNode(self,root,key):
if root is None:
return root
if key < root.key:
root.l = self.deleteNode(root.l,key)
elif(key > root.key):
root.right =self.deleteNode(root.r,key)
else:
if root.l is None :
temp = root.r
root = None
return temp
elif root.r is None :
temp = root.l
root = None
return temp
temp = minValueNode(root.r)
root.key = temp.key
root.r =self.deleteNode(root.r,temp.key)
return root
b=BST()
print("******************TREE USING DOUBLE LINKED LIST************************")
while True:
print("1.Insertion \n2.Post Order Traversal\n3.Pre Order Traversal")
print("4.In Order Traversal\n5.Leaf Node of Tree\n6.Height of Tree\n7.Non-Leaf Node")
print("8.Searching\n9.Deleting\n10.Exit")
ch=int(input("Enter choice:"))
26 | P a g e
if ch==1:
data=eval(input("Enter data:"))
b.insert(data)
elif ch==2:
b.postorder(b.root)
elif ch==3:
b.preorder(b.root)
elif ch==4:
b.inorder(b.root)
elif ch==5:
b.leafnode(b.root)
elif ch==6:
print(b.height(b.root))
elif ch==7:
b.nleafnode(b.root)
elif ch==8:
n=eval(input("Enter search element:"))
b.searching(b.root,n)
elif ch==9:
data=eval(input("Enter delete element:"))
b.deleteNode(b.root,data)
print(data,"Deleted")
else:
print("Exit")
break
7.6 INPUT/ OUTPUT
27 | P a g e
7.7 LAB VIVA QUESTIONS:
28 | P a g e
WEEK-8
GRAPH TRAVERSALS
8.1 OBJECTIVE:
1. Print all the nodes reachable from a given starting node in a digraph using BFS method.
8.2 RESOURCES:
IDLE(python GUI)
Breadth First Search (BFS) algorithm traverses a graph in a breadth ward motion and uses a
queue to remember to get the next vertex to start a search.
1. Visit the adjacent unvisited vertex. Mark it as visited. Display it. Insert it in a queue.
2. If no adjacent vertex is found, remove the first vertex from the queue.
3. Repeat Rule 1 and Rule 2 until the queue is empty.
29 | P a g e
Depth first traversal
Depth First Search (DFS) algorithm traverses a graph in a depth ward motion and uses a stack to
remember to get the next vertex to start a search.
1. Visit the adjacent unvisited vertex. Mark it as visited. Display it. Push it in a stack.
2. If no adjacent vertex is found, pop up a vertex from the stack. (It will pop up all the vertices
from the stack, which do not have adjacent vertices.)
3. Repeat Rule 1 and Rule 2 until the stack is empty.
8.4 PROCEDURE:
1. Create: Open IDLE(python GUI), write a program after that save the program with .c extension.
2. Run Module(F5)
class Vertex:
def __init__(self, data) :
self.data = data
self.nxtVertex = None
self.AdjHead = None
self.trvState = None
class AdjNode :
def __init__(self) :
self.reference = None
self.nxt = None
class Graph :
def __init__(self) :
self.root = None
self.vertexCtr = 0
def create(self) :
# Creation of AdjacetList
temp = self.root
30 | P a g e
while temp is not None :
print('Enter the Adjacency List of Vertex(',temp.data,')')
adjLst = input('Enter Here (In Ascending order : ) : ').split()
for i in range(len(adjLst)) :
refPtr = self.getReference(adjLst[i])
new_node = AdjNode()
new_node.reference = refPtr
if temp.AdjHead == None :
temp.AdjHead = new_node
else :
temp1 = temp.AdjHead
while temp1.nxt is not None :
temp1 = temp1.nxt
temp1.nxt = new_node
temp = temp.nxtVertex
return temp
temp = temp.nxtVertex
def LinearSearch(self, Lst, Key) :
for i in range(len(Lst)) :
if Lst[i] == Key :
return True
return False
def DFT(self) :
Path = []
S = []
V = self.root
S.append(V)
while len(S) is not 0 :
V = S.pop()
if self.LinearSearch(Path, V.data) == False :
Path.append(V.data)
temp = V.AdjHead
while temp is not None :
S.append(temp.reference)
temp = temp.nxt
return Path
def BFT(self) :
Path = []
S = []
V = self.root
S.append(V)
while len(S) is not 0 :
V = S.pop(0)
if self.LinearSearch(Path, V.data) == False :
Path.append(V.data)
temp = V.AdjHead
31 | P a g e
while temp is not None :
S.append(temp.reference)
temp = temp.nxt
return Path
#Driver Code
print("######---Graph---#####")
G = Graph()
G.create()
print('**************Graph Traversals :*************')
print('\t1. Depth First Traversal')
print('\t2. Breadth First Traveral')
while True :
ch = int(input('Enter Choice : '))
if ch == 1 :
print(G.DFT())
elif ch == 2 :
print(G.BFT())
else:
print("Exit")
break
32 | P a g e
8.6 INPUT/ OUTPUT
WEEK-9
9.1 OBJECTIVE:
Find a subset of a given set S = {sl, s2.....sn} of n positive integers whose sum is equal to a given
positive integer d. For example, if S= {1, 2, 5, 6, 8} and d = 9 there are two solutions {1, 2, 6} and {1,
8}.A suitable message is to be displayed if the given problem instance doesn't have a solution.
9.2 RESOURCES:
IDLE(python GUI)
33 | P a g e
9.3 PROGRAM LOGIC:
Given a set of non-negative integers, and a value sum, determine if there is a subset of the given set
with sum equal to given sum.
9.4 PROCEDURE:
1. Create: Open IDLE(python GUI), write a program after that save the program with .c extension.
2. Run Module(F5)
34 | P a g e
9.6 INPUT/ OUTPUT
1. Define is Back-Tracking.
2. Explain Sum of subset problem.
3. What is time complexity of sum of subset problem?
35 | P a g e
WEEK-10
10.1 OBJECTIVE:
Implement any scheme to find the optimal solution for the Traveling Sales Person problem and then
solve the same problem instance using any approximation algorithm and determine the error in the
approximation
10.2 RESOURCES:
IDLE(python GUI)
1. Check for the disconnection between the current city and the next city
2. Check whether the travelling sales person has visited all the cities
3. Find the next city to be visited
4. Find the solution and terminate
10.4 PROCEDURE:
1. Create: Open IDLE(python GUI), write a program after that save the program with .c extension.
2. Run Module(F5)
10.5 SOURCE CODE:
36 | P a g e
if x==999:
x=0
print(x+1)
cost=cost+a[c][x]
return
mincost(x)
def least(u):
global cost
mini=v=999
for i in range(n):
if a[u][i]!=0 and visit[i]==0:
if a[u][i]+a[i][u]<mini:
mini=a[i][u]+a[u][i]
kmin=a[u][i]
v=i
if mini!=999:
cost=cost+kmin
return v
main()
print("Minimum Cost is : ",cost)
11.1 OBJECTIVE:
Find Minimum Cost Spanning Tree of a given undirected graph using Prim’s algorithm.
11.2 RESOURCES:
IDLE(python GUI)
a) Pick a vertex u which is not there in Sand has minimum key value.
b) Include u to S.
c) Update key value of all adjacent vertices of u.
To update the key values, iterate through all adjacent vertices. For every adjacent vertex v, if
weight of edge u-v is less than the previous key value of v, update the key value as weight of u-v
The idea of using key values is to pick the minimum weight edge from cut. The key values are used
only for vertices which are not yet included in MST, the key value for these vertices indicate the
minimum weight edges connecting them to the set of vertices included in MST.
11.4 PROCEDURE:
1. Create: Open IDLE(python GUI), write a program after that save the program with .c extension.
2. Run Module(F5)
38 | P a g e
11.5 SOURCE CODE.
maxi=9999999
n=int(input("Enter the number of nodes:"))
selected=[False for i in range(n)]
def main(n,cost):
n_edge=0
selected[0]=True
while n_edge<n-1:
minimum=maxi
x=y=0
for i in range(n):
if selected[i]:
for j in range(n):
if not selected[j] and cost[i][j]:
if minimum>cost[i][j]:
minimum=cost[i][j]
x=i
y=j
print(x,'-->',y,':',cost[x][y])
selected[y]=True
n_edge+=1
cost=[[int(x) for x in input().split()]
for j in range(n)]
for i in range(n):
for j in range(n):
if cost[i][j]==0:
cost[i][j]=maxi
print("The shortest path using Prim's Algorithm is :\n")
main(n,cost)
39 | P a g e
11.6 INPUT/ OUTPUT
40 | P a g e
WEEK-12
12.1 OBJECTIVE:
12.2 RESOURCES:
IDLE(python GUI)
Initialize the solution matrix same as the input graph matrix as a first step. Then we update the
solution matrix by considering all vertices as an intermediate vertex. The ideas is to one by one pick
all vertices and update all shortest paths which include the picked vertex as an intermediate vertex in
the shortest path.
When we pick vertex number k as an intermediate vertex, we already have considered vertices
{0, 1, 2, .. k-1} as intermediate vertices.
For every pair (i, j) of source and destination vertices respectively, there are two possible cases.
1) k is not an intermediate vertex in shortest path from i to j. We keep the value of dist[i][j] as it is.
12.4 PROCEDURE:
1. Create: Open IDLE(python GUI), write a program after that save the program with .c extension.
2. Run Module(F5)
41 | P a g e
12.5 SOURCE CODE.
n=int(input("Enter the
number of nodes:"))
graph=[[0 for i in range(n)]
for j in range(n)]
print("Enter the adjacency
matrix in boolean values:")
for i in range(n):
for j in range(n):
temp=int(input())
graph[i][j]=temp
print("The adjacency matrix
in boolean values:")
for i in range(n):
for j in range(n):
print(graph[i][j],end="\t")
print("\n")
for k in range(n):
for i in range(n):
for j in range(n):
if graph[i][k]==1
and graph[k][j]==1:
graph[i][j]=1
print("*******WARSHAL
L'S TRANSITIVE
CLOSURE********")
for i in range(n):
for j in range(n):
print(graph[i][j],end="\t")
print("\n")
42 | P a g e
12.6 INPUT/ OUTPUT
43 | P a g e
WEEK-13
N QUEENS PROBLEM
13.1 OBJECTIVE:
13.2 RESOURCES:
IDLE(python GUI)
13.4 PROCEDURE:
1. Create: Open IDLE(python GUI), write a program after that save the program with .c extension.
2. Run Module(F5)
1. Define backtracking.
2. Define live node, dead node.
3. Define implicit and explicit constraints.
4. What is the time complexity of n-queens problem.
45 | P a g e