ADS Record Programs
ADS Record Programs
Write a program to find minimum cost spanning tree using Prim’s algorithm
classGraph():
def__init__(self, vertices):
self.V =vertices
self.graph =[[0forcolumn inrange(vertices)]
forrow inrange(vertices)]
forv inrange(self.V):
ifkey[v] < minandmstSet[v] ==False:
min=key[v]
min_index =v
returnmin_index
forcout inrange(self.V):
1
# 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)
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();
Expected Output:
Edge Weight
0-1 2
1-2 3
0-3 6
1-4 5
2
8. Write a program to find minimum cost spanning tree using Kruskal’s algorithm
3
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'salgorithm
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)
4
y = self.find(parent, v)
# If including this edge does't
# cause cycle, include it in result
# and increment the indexof result
# for next edge
if x != y:
e=e+1
result.append([u, v, w])
self.union(parent, rank, x, y)
# Else discard the 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:
Following are the edges in the constructed MST
2 -- 3 == 4
0 -- 3 == 5
0 -- 1 == 10
Minimum Cost Spanning Tree: 19
5
9. Write a program to find a single source shortest path for a given graph.
importsys
classGraph():
def__init__(self, vertices):
self.V =vertices
self.graph =[[0forcolumn inrange(vertices)]
forrow inrange(vertices)]
defprintSolution(self, dist):
print("Vertex \tDistance from Source")
fornode inrange(self.V):
print(node, "\t", dist[node])
returnmin_index
forcout inrange(self.V):
6
# Put the minimum distance vertex in the
# shortest path tree
sptSet[x] =True
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.dijkstra(0);
Output:
7
10. Write a program to find the solution for job sequencing with deadlines problems
# Program to find the maximum profitjob sequence from a given array of jobs
with deadlines and profitsfunction to schedule the jobs take 2arguments
array and no of jobs to schedule
defprintJobScheduling(arr, t):
# length of array
n =len(arr)
# Sort all jobs according to
# decreasing order of profit
fori inrange(n):
forj inrange(n -1-i):
ifarr[j][2] < arr[j +1][2]:
arr[j], arr[j +1] =arr[j +1], arr[j]
# To keep track of free time slots
result =[False] *t
# To store result (Sequence of jobs)
job =['-1'] *t
# Iterate through all given jobs
fori inrange(len(arr)):
# Find a free slot for this job
# (Note that we start from the
# last possible slot)
forj inrange(min(t -1, arr[i][1] -1), -1, -1):
# Free slot found
ifresult[j] isFalse:
result[j] =True
job[j] =arr[i][0]
break
# print the sequence
print(job)
# Driver COde
arr =[['a', 2, 100], # Job Array
['b', 1, 19],
['c', 2, 27],
['d', 1, 25],
['e', 3, 15]]
print("Following is maximum profit sequence of jobs")
# Function Call
printJobScheduling(arr, 3)
Output:
8
12. Write a program to solve Sum of subsets problem for a given set of distinct numbers using
backtracking.
# exclude the current element from the current subset and recur
printPowerSet(S, i - 1, out)
if __name__ == '__main__':
S = [1, 3, 1]
findPowerSet(S)
Output:
[3, 1, 1]
[3, 1]
[3]
[1, 1]
[1]
9
[]
defprintSolution(board):
fori inrange(N):
forj inrange(N):
print(board[i][j], end =" ")
print()
returnTrue
defsolveNQUtil(board, col):
10
ifisSafe(board, i, col):
defsolveNQ():
board =[ [0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0] ]
ifsolveNQUtil(board, 0) ==False:
print("Solution does not exist")
returnFalse
printSolution(board)
returnTrue
# Driver Code
solveNQ()
0 0 1 0
1 0 0 0
0 0 0 1
0 1 0 0
11