0% found this document useful (0 votes)
127 views49 pages

Daa LM Practical Exercises

DAA Lab manual

Uploaded by

karthiga
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)
127 views49 pages

Daa LM Practical Exercises

DAA Lab manual

Uploaded by

karthiga
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/ 49

PRACTICAL EXERCISES:

1. Implement recursive and non-recursive algorithms and study the


order of growth from log2n to n!.
2. Divide and Conquer - Strassen’s Matrix Multiplication
3. Decrease and Conquer - Topological Sorting
4. Transform and Conquer - Heap Sort
5. Dynamic programming - Coin change Problem,
Warshall’s and Floyd‘s algorithms, Knapsack Problem
6. Greedy Technique – Dijkstra’s algorithm, Huffman Trees and codes
7. Iterative improvement - Simplex Method
8. Backtracking – N-Queen problem, Subset Sum Problem
9. Branch and Bound - Assignment problem, Traveling Salesman Problem
Exp No: 1
IMPLEMENT RECURSIVE AND NON-RECURSIVE ALGORITHMS
Date:

AIM
The Aim is to implement recursive and non-recursive algorithms and study the order of growth
from log2n to n!
ALGORITHM
Step 1: Start the program.
Step 2: Implement recursive and non-recursive algorithms using log2n to n!
Step 3: Compute Factorial n*fact(n-1),Fibonacci series using recursive algorithm
Step 5: Compute the insertion sort using non recursive algorithm
Step 6: End the program
PROGRAM
1. A) Python code to implement Factorial
def recursive_factorial(n):
if n == 1:
return n
else:
return n * recursive_factorial(n-1)
num = 6
if num < 0:
print("Invalid input ! Please enter a positive number.")
elif num == 0:
print("Factorial of number 0 is 1")
else:
print("Factorial of number", num, "=", recursive_factorial(num))

OUTPUT
Factorial of number 6 = 720
2. B) Python code to implement Fibonacci series

def recursive_fibonacci(n):
if n <= 1:
return n
else:
return(recursive_fibonacci(n-1) + recursive_fibonacci(n-2))
n_terms = 10
# check if the number of terms is valid
if n_terms <= 0:
print("Invalid input ! Please input a positive value")
else:
print("Fibonacci series:")
for i in range(n_terms):
print(recursive_fibonacci(i))

OUTPUT
Fibonacci series:
0
1
1
2
3
5
8
13
21
34
NON-RECURSIVE ALGORITHM

3. C) Python program for implementation of Insertion Sort

def insertionSort(arr):
n = len(arr)
if n <= 1:
return

for i in range(1, n):


key = arr[i]
j = i-1
while j >= 0 and key < arr[j]:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
arr = [12, 11, 13, 5, 6]
insertionSort(arr)
print(arr)

OUTPUT
Insertion sort

Sorted array is: [5, 6, 11, 12, 13]

RESULT
Thus, program for recursive and non-recursive algorithm are given above are executed
successfully.
Exp No: 2 STRASSEN’S MATRIX MULTIPLICATION USING DIVIDE AND
Date: CONQUER

AIM
The Aim is to implement recursive and non-recursive algorithms and study the order of growth
from log2n to n!
ALGORITHM
Step 1: Start the program.
Step 2: Divide the matrices A and B into smaller sub matrices of the size n/2xn/2
Step 3: Using the formula of scalar additions and subtractions compute smaller matrices of size
n/2.
Step 4: Recursively compute the seven matrix products Pi=AiBi for i=1,2,…
Step 5: End the program
PROGRAM
x=[[0,2],[0,1]]
print("matrix x is:")
for i in range(len(x)):
print("\t",x[i])
y=[[0,0],[3,4]]
print("matrix y is:")
for i in range(len(y)):
print("\t",y[i])
def strassen(a,b):
S=[b[0][1]-b[1][1],
a[0][0]+a[0][1],
a[1][0]+a[1][1],
b[1][0]-b[0][0],
a[0][0]+a[1][1],
b[0][0]+b[1][1],
a[0][1]-a[1][1],
b[1][0]+b[1][1],
a[0][0]-a[1][0],
b[0][0]+b[0][1]]
P=[a[0][0]*S[0],
S[1]*b[1][1],
S[2]*b[0][0],
a[1][1]*S[3],
S[4]*S[5],
S[6]*S[7],
S[8]*S[9]]
C=[[P[4]+P[3]-P[1]+P[5],P[0]+P[1]],
[P[2]+P[3],
P[4]+P[0]-P[2]-P[6]]]
print("Strassen's Matrix multiplication of x and y is.")
print(S)
print(P)
print(C)
strassen(x,y)

OUTPUT:
Matrix X is : [0,2]
[0,1]
Matrix Y is : [0,0]
[3,4]
Strassen's Matrix multiplication of x and y is.
[-4,2,1,3,1,4,1,7,0,0]
[0,8,0,3,4,7,0]
[[6,8],[3,4]]

RESULT :
Thus the above program has been executed successfully and the required output is displayed.
Exp No: 3
DIVIDE AND CONQUER – TOPOLOGICAL SORTING
Date:

AIM
To implement Decrease and Conquer - Topological Sorting
ALGORITHM
Step 1: Create a stack to store the nodes.
Step 2: Initialize visited an array of size N to keep the record of visited nodes.
Step 3: Run a loop from 0 to N.
Step 4: if the node is not marked True in the visited array.
Step 5: Call the recursive function for topological sort and perform the following steps.
Step 6: Mark the current node as True in the visited array.
Step 7: Run a loop on all the nodes which have a directed edge to the current node.
Step 8: if the node is not marked true in the visited array: Recursively call the topological sort
function on the node and Push the current node in the stack.
Step 9: Print all the elements in the stack.
PROGRAM
from collections import defaultdict
class Graph:
def __init__(self,n):
self.graph = defaultdict(list)
self.N = n
def addEdge(self,m,n):
self.graph[m].append(n)
def sortUtil(self,n,visited,stack):
visited[n] = True
for element in self.graph[n]:
if visited[element] == False:
self.sortUtil(element,visited,stack)
stack.insert(0,n)
def topologicalSort(self):
visited = [False]*self.N
stack =[]
for element in range(self.N):
if visited[element] == False:
self.sortUtil(element,visited,stack)
print(stack)
graph = Graph(5)
graph.addEdge(0,1)
graph.addEdge(0,3)
graph.addEdge(1,2)
graph.addEdge(2,3)
graph.addEdge(2,4)
graph.addEdge(3,4)
print("The Topological Sort Of The Graph Is: ")
graph.topologicalSort()
OUTPUT:
The Topological Sort Of The Graph Is:
[0, 1, 2, 3, 4]

RESULT
Thus the above program has been executed successfully and the required output is displayed.
Exp No: 4
TRANSFORM AND CONQUER – HEAP SORT
Date:

AIM
To write a python program to Transform and Conquer - Heap Sort.
ALGORITHM
Step 1: First convert the array into a heap data structure using heapify
Step 2: one by one delete the root node of the Max-heap and replace it with the last node in the
heap and then heapify the root of the heap.
Step 3: Repeat this process until the size of the heap is greater than 1.
Step 4: Build a max heap from the input data.
Step 5: At this point, the maximum element is stored at the root of the heap. Step 6: Replace it
with the last item of the heap followed by reducing the size of the heap by 1.
Step 7: Finally, heapify the root of the tree.
Step 8: Repeat step 2 while the size of the heap is greater than 1.
PROGRAM
def heapify(arr, n, i):
largest = i
l=2*i+1
r=2*i+2
if l < n and arr[i] < arr[l]:
largest = l
if r < n and arr[largest] < arr[r]:
largest = r
if largest != i:
arr[i],arr[largest] = arr[largest],arr[i]
heapify(arr, n, largest)
def heapSort(arr):
n = len(arr)
for i in range(n, -1, -1):
heapify(arr, n, i)
for i in range(n-1, 0, -1):
arr[i], arr[0] = arr[0], arr[i]
heapify(arr, i, 0)
arr = [2,5,3,8,6,5,4,7]
heapSort(arr)
n = len(arr)
print ("Sorted array is")
for i in range(n):
print (arr[i],end=" ")
OUTPUT:
Sorted array is
23455678

RESULT
Thus the above program has been executed successfully and the required output is displayed.
Exp No: 5(a)
DYNAMIC PROGRAMMING - COIN CHANGE PROBLEM
Date:

AIM

To write a python program to Dynamic programming - Coin change Problem

ALGORITHM

Step 1: Start the program.

Step 2: Create an array[i], it represents the number of ways to make the sum i using the given
coin denominations.
Step 3: The outer loop iterates over the coins, and the inner loop iterates over the target sums.
For each array[j], it calculates the number of ways to make change using the current coin
denomination and the previous results stored in array[j].
Step 4: Array [sum] contains the total number of ways to make change for the given target sum
using the available coin denominations.
Step 5: Finally print no ways the coin given.
Step 6: Stop the program.
5a) PROGRAM
def getNumberOfWays(N, Coins):
ways = [0] * (N + 1);
ways[0] = 1;
for i in range(len(Coins)):
for j in range(len(ways)):
if (Coins[i] <= j):
ways[j] += ways[(int)(j - Coins[i])];
return ways[N];
def printArray(coins):
for i in coins:
print(i);
if __name__ == '__main__':
Coins = [1, 5, 10];
print("The Coins Array:");
printArray(Coins);
print("Solution:",end="");
print(getNumberOfWays(2, Coins));
OUTPUT:
The Coins Array:
1
5
10
Solution: 1

RESULT
Thus the above program has been executed successfully and the required output is displayed.
Exp No: 5(b)
DYNAMIC PROGRAMMING – FLOYD WARSHALL’S ALGORITHM
Date:

AIM

To write a python program to Dynamic programming - Floyd Warshall’s Algorithm

ALGORITHM

Step 1: Create a matrix A0 of dimension n*n where n is the number of vertices. The row and the
column are indexed as i and j respectively. i and j are the vertices of the graph.
Step 2: Each cell A[i][j] is filled with the distance from the ith vertex to the jth vertex. If there is
no path from ith vertex to jth vertex, the cell is left as infinity.

Step 3: Create a matrix A1 using matrix A0. The elements in the first column and the first row
are left as they are. The remaining cells are filled in the following way.

i) Let k be the intermediate vertex in the shortest path from source to destination. In this
step, k is the first vertex. A[i][j] is filled with (A[i][k] + A[k][j]) if (A[i][j] > A[i][k] +
A[k][j]).

ii) That is, if the direct distance from the source to the destination is greater than the path
through the vertex k, then the cell is filled with A[i][k] + A[k][j].

iii) In this step, k is vertex 1. We calculate the distance from source vertex to destination
vertex through this vertex k.

Step 4: Similarly, A2 is created using A1. The elements in the second column and the second
row are left as they are.

Step 5: Similarly, A3 and A4 is also created

Step 6: Print A4 and it gives the shortest path between each pair of vertices.

Step 7: Stop the program.


PROGRAM

nV = 4
INF = 999
def floyd_warshall(G):
distance = list(map(lambda i: list(map(lambda j: j, i)), G))
for k in range(nV):
for i in range(nV):
for j in range(nV):
distance[i][j] = min(distance[i][j], distance[i][k] + distance[k][j])
print_solution(distance)
def print_solution(distance):
for i in range(nV):
for j in range(nV):
if(distance[i][j] == INF):
print("INF", end=" ")
else:
print(distance[i][j], end=" ")
print(" ")
G = [[0, 3, INF, 5],
[2, 0, INF, 4],
[INF, 1, 0, INF],
[INF, INF, 2, 0]]
floyd_warshall(G)
OUTPUT
0 3 7 5
2 0 6 4
3 1 0 5
5 3 2 0

RESULT
Thus the above program has been executed successfully and the required output is
displayed.
Exp No: 5(c)
DYNAMIC PROGRAMMING – KNAPSACK PROBLEM
Date:

AIM

To write a python program to Dynamic programming – knapsack problem

ALGORITHM

Step 1: Start the program.

Step 2: Include the Nth item. Value of the Nth item plus maximum value obtained by remaining
N-1 items and remaining weight i.e. (W-weight of the Nth item).

Step 3: Exclude the Nth item. Maximum value obtained by N-1 items and W weight.

Step 4: If the weight of the ‘Nth‘ item is greater than ‘W’, then the Nth item cannot be included
and in Step 3 is the only possibility.
Step 5: Stop the program.
PROGRAM
def knapsack(wt, val, W, n):
if n == 0 or W == 0:
return 0
if t[n][W] != -1:
return t[n][W]
if wt[n-1] <= W:
t[n][W] = max(
val[n-1] + knapsack(
wt, val, W-wt[n-1], n-1),
knapsack(wt, val, W, n-1))
return t[n][W]
elif wt[n-1] > W:
t[n][W] = knapsack(wt, val, W, n-1)
return t[n][W]
if __name__ == '__main__':
profit = [60, 100, 120]
weight = [10, 20, 30]
W = 75
n = len(profit)
t = [[-1 for i in range(W + 1)] for j in range(n + 1)]
print(knapsack(weight, profit, W, n))
OUTPUT:
280

RESULT
Thus the above program has been executed successfully and the required output is
displayed.
Exp No: 6(a)
GREEDY TECHNIQUE – DIJKSTRA’S ALGORITHM
Date:

AIM

To write a python program to Greedy Technique – Dijkstra’s Algorithm.

ALGORITHM

Step 1: Start the program.


Step 2: Create a set sptSet (shortest path tree set) that keeps track of vertices included in the
shortest path tree, i.e., whose minimum distance from the source is calculated and finalized.
Initially, this set is empty.
Step 3: Assign a distance value to all vertices in the input graph. Initialize all distance values
as INFINITE. Assign the distance value as 0 for the source vertex so that it is picked first.
Step 4: While sptSet doesn’t include all vertices
i) Pick a vertex u that is not there in sptSet and has a minimum distance value.
ii) Include u to sptSet.
iii) Then update the distance value of all adjacent vertices of u.
a. To update the distance values, iterate through all adjacent vertices.
b. For every adjacent vertex v, if the sum of the 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.
Step 5: Stop the program.
PROGRAM
import sys
class Graph():
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)]
for row in range(vertices)]
def printSolution(self, dist):
print("Vertex \tDistance from Source")
for node in range(self.V):
print(node, "\t", dist[node])
def minDistance(self, dist, sptSet):
min = sys.maxsize
for u in range(self.V):
if dist[u] < min and sptSet[u] == False:
min = dist[u]
min_index = u
return min_index
def dijkstra(self, src):
dist = [sys.maxsize] * self.V
dist[src] = 0
sptSet = [False] * self.V
for cout in range(self.V):
x = self.minDistance(dist, sptSet)
sptSet[x] = True
for y in range(self.V):
if self.graph[x][y] > 0 and sptSet[y] == False and \
dist[y] > dist[x] + self.graph[x][y]:
dist[y] = dist[x] + self.graph[x][y]
self.printSolution(dist)
if __name__ == "__main__":
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

Vertex Distance from Source


0 0
1 4
2 12
3 19
4 21
5 11
6 9
7 8
8 14

RESULT
Thus the above program has been executed successfully and the required output is displayed.
Exp No: 6(b)
GREEDY TECHNIQUE – HUFFMAN TREES AND CODES
Date:

AIM

To write a python program to Greedy Technique – Huffman Trees and codes

ALGORITHM

Step 1: Start the program.


Step 2: Create a leaf node for each unique character and build a min heap of all leaf nodes (Min
Heap is used as a priority queue. The value of frequency field is used to compare two nodes in
min heap. Initially, the least frequent character is at root)
Step 3: Extract two nodes with the minimum frequency from the min heap.
Step 4: Create a new internal node with a frequency equal to the sum of the two nodes
frequencies. Make the first extracted node as its left child and the other extracted node as its right
child. Add this node to the min heap.
Step 5: Repeat steps 3 and 4 until the heap contains only one node. The remaining node is the
root node and the tree is complete.
Step 6: Print the Huffman frequency and code
Step 7: Stop the program.
PROGRAM:
import heapq
class node:
def __init__(self, freq, symbol, left=None, right=None):
self.freq = freq
self.symbol = symbol
self.left = left
self.right = right
self.huff = ''
def __lt__(self, nxt):
return self.freq < nxt.freq
def printNodes(node, val=''):
newVal = val + str(node.huff)
if(node.left):
printNodes(node.left, newVal)
if(node.right):
printNodes(node.right, newVal)
if(not node.left and not node.right):
print(f"{node.symbol} -> {newVal}")
chars = ['a', 'b', 'c', 'd', 'e', 'f']
freq = [5, 9, 25, 13, 16, 85]
nodes = []
for x in range(len(chars)):
heapq.heappush(nodes, node(freq[x], chars[x]))
while len(nodes) > 1:
left = heapq.heappop(nodes)
right = heapq.heappop(nodes)
left.huff = 0
right.huff = 1
newNode = node(left.freq+right.freq, left.symbol+right.symbol, left, right)
heapq.heappush(nodes, newNode)
printNodes(nodes[0])

OUTPUT
d -> 000
a -> 0010
b -> 0011
e -> 010
c -> 011
f -> 1

RESULT
Thus the above program has been executed successfully and the required output is displayed.
Exp No: 7
ITERATIVE IMPROVEMENT - SIMPLEX METHOD
Date:

AIM

To write a program to implement Iterative improvement - Simplex Method.

ALGORITHM

Step 1: Start with the initial basis associated with the identity matrix.

Step 2: Calculate the relative profits.

i) For MAX problem, If all the relative profits are less than or equal to 0, then the
current basis is the optimal one. STOP. Else continue to 3.

ii) For MIN problem, if all the relative profits are greater than or equal to 0, then the
current basis is the optimal one. STOP. Else continue to 3.

Step 3: Find the column corresponding to max relative profit. Say column k has the max Rel.
profit. So xk will enter the basis.

Step 4: Perform a min ratio test to determine which variable will leave the basis. min ratio test:
XBr/y_{rk} = min{XB_i/y_{ik}}.The index of the min element i 'r' will determine the leaving
variable. The basic variable at index r will leave the basis.

Step 5: It's evident that the entered variable will not form an identity matrix, so we will have to
perform row operations to make it identity again.

Step 6: Find the pivot element. The element at index (r, k) will be the pivot element and row r
will be the pivot row.

Step 7: Divide the rth row by pivot to make it 1. And subtract c*(rth row) from other rows to
make them 0, where c is the coefficient required to make that row 0.

Step 8: Stop the program.


PROGRAM
import numpy as np
from fractions import Fraction
print("\n****SiMplex Algorithm ****\n\n")
A = np.array([[1, 1, 0, 1], [2, 1, 1, 0]])
b = np.array([8, 10])
c = np.array([1, 1, 0, 0])
cb = np.array(c[3])
B = np.array([[3], [2]])
cb = np.vstack((cb, c[2]))
xb = np.transpose([b])
table = np.hstack((B, cb))
table = np.hstack((table, xb))
table = np.hstack((table, A))
table = np.array(table, dtype ='float')
MIN = 0
print("Table at itr = 0")
print("B \tCB \tXB \ty1 \ty2 \ty3 \ty4")
for row in table:
for el in row:
print(Fraction(str(el)).limit_denominator(100), end ='\t')
print()
print()
print("Simplex Working....")
reached = 0
itr = 1
unbounded = 0
alternate = 0
while reached == 0:
print("Iteration: ", end =' ')
print(itr)
print("B \tCB \tXB \ty1 \ty2 \ty3 \ty4")
for row in table:
for el in row:
print(Fraction(str(el)).limit_denominator(100), end ='\t')
print()
i=0
rel_prof = []
while i<len(A[0]):
rel_prof.append(c[i] - np.sum(table[:, 1]*table[:, 3 + i]))
i=i+1
print("rel profit: ", end =" ")
for profit in rel_prof:
print(Fraction(str(profit)).limit_denominator(100), end =", ")
print()
i=0
b_var = table[:, 0]
while i<len(A[0]):
j=0
present = 0
while j<len(b_var):
if int(b_var[j]) == i:
present = 1
break;
j+= 1
if present == 0:
if rel_prof[i] == 0:
alternate = 1
print("Case of Alternate found")
i+= 1
print()
flag = 0
for profit in rel_prof:
if profit>0:
flag = 1
break
if flag == 0:
print("All profits are <= 0, optimality reached")
reached = 1
break
k = rel_prof.index(max(rel_prof))
min = 99999
i = 0;
r = -1
while i<len(table):
if (table[:, 2][i]>0 and table[:, 3 + k][i]>0):
val = table[:, 2][i]/table[:, 3 + k][i]
if val<min:
min = val
r=i
i+= 1
if r ==-1:
unbounded = 1
print("Case of Unbounded")
break
print("pivot element index:", end =' ')
print(np.array([r, 3 + k]))
pivot = table[r][3 + k]
print("pivot element: ", end =" ")
print(Fraction(pivot).limit_denominator(100))
table[r, 2:len(table[0])] = table[
r, 2:len(table[0])] / pivot
i=0
while i<len(table):
if i != r:
table[i, 2:len(table[0])] = table[i,2:len(table[0])] - table[i][3 + k] *table[r, 2:len(table[0])]
i += 1
table[r][0] = k
table[r][1] = c[k]
print()
print()
itr+= 1
print()
print("***************************************************************")
if unbounded == 1:
print("UNBOUNDED LPP")
exit()
if alternate == 1:
print("ALTERNATE Solution")
print("optimal table:")
print("B \tCB \tXB \ty1 \ty2 \ty3 \ty4")
for row in table:
for el in row:
print(Fraction(str(el)).limit_denominator(100), end ='\t')
print()
print()
print("value of Z at optimality: ", end =" ")
basis = []
i=0
sum = 0
while i<len(table):
sum += c[int(table[i][0])]*table[i][2]
temp = "x"+str(int(table[i][0])+1)
basis.append(temp)
i+= 1
if MIN == 1:
print(-Fraction(str(sum)).limit_denominator(100))
else:
print(Fraction(str(sum)).limit_denominator(100))
print("Final Basis: ", end =" ")
print(basis)
print("Simplex Finished...")
print()
OUTPUT
**** Simplex Algorithm ****
Table at itr = 0
B CB XB y1 y2 y3 y4 3 0 8 1 1 0 1 2 0 10 2 1 1
0 Simplex Working....
Iteration: 1
B CB XB y1 y2 y3 y4 3 0 8 1 1 0 1 2 0 10 2 1 1
0 rel profit: 1, 1, 0, 0,
Pivot element index: [1 3]
Pivot element: 2
Iteration: 2
B CB XB y1 y2 y3 y4 3 0 3 0 1/2 -1/2 1 0 1 5 1
1/2 1/2 0 rel profit: 0, 1/2, -1/2, 0,
Pivot element index: [0 4]
Pivot element: 1/
Iteration: 3
B CB XB y1 y2 y3 y 1 1 6 0 1 -1 2
012101-
rel profit: 0, 0, 0, -1,
Case of Alternate found
All profits are <= 0, optimality reached
ALTERNATE Solution
Optimal table:
B CB XB y1 y2 y3 y
1 1 6 0 1 -1 2
012101-
Value of Z at optimality: 8
Final Basis: ['x2', 'x1']
Simplex Finished..

RESULT:
Thus the above program has been executed successfully and the required output is displayed.
Exp No: 8(a)
BACKTRACKING – N-QUEEN PROBLEM
Date:

AIM

To write a python program to Backtracking – N-Queen problem

ALGORITHM

Step 1: Start the program.


Step 2: Start in the leftmost column
Step 3: If all queens are placed return true
Step 4: Try all rows in the current column. Do the following for every row.
 If the queen can be placed safely in this row
i) Then mark this [row, column] as part of the solution and recursively check if
placing queen here leads to a solution.
ii) If placing the queen in [row, column] leads to a solution then return true.
iii) If placing queen doesn’t lead to a solution then unmark this [row,
column] then backtrack and try other rows.
 If all rows have been tried and valid solution is not found return false to trigger
backtracking.
Step 5: Stop the program
PROGRAM
global N
N=4
def printSolution(board):
for i in range(N):
for j in range(N):
if board[i][j] == 1:
print("Q",end=" ")
else:
print(".",end=" ")
print()
def isSafe(board, row, col):
for i in range(col):
if board[row][i] == 1:
return False
for i, j in zip(range(row, -1, -1),
range(col, -1, -1)):
if board[i][j] == 1:
return False
for i, j in zip(range(row, N, 1),
range(col, -1, -1)):
if board[i][j] == 1:
return False

return True
def solveNQUtil(board, col):
if col >= N:
return True
for i in range(N):
if isSafe(board, i, col):
board[i][col] = 1
if solveNQUtil(board, col + 1) == True:
return True
board[i][col] = 0
return False
def solveNQ():
board = [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
if solveNQUtil(board, 0) == False:
print("Solution does not exist")
return False
printSolution(board)
return True
if __name__ == '__main__':
solveNQ()
OUTPUT

. . Q .
Q . . .
. . . Q
. Q . .

RESULT:
Thus the above program has been executed successfully and the required output is displayed.
Exp No: 8(b)
BACKTRACKING – SUBSET SUM PROBLEM
Date:

AIM

To write a python program to Backtracking – Subset Sum Problem

ALGORITHM

Step 1: Start the program.


Step 2: Include the current element in the subset and recur for the remaining elements with the
remaining Sum. Exclude the current element from the subset and recur for the remaining
elements.
Step 3: Finally, if Sum becomes 0 then print the elements of current subset. The recursion’s base
case would be when no items are left, or the sum becomes negative, then simply return.

Step 4: Stop the program.


PROGRAM
def print_subset_sum(i, n, _set, target_sum, subset):
global flag
if target_sum == 0:
flag = True
print("[", end=" ")
for element in subset:
print(element, end=" ")
print("]", end=" ")
return
if i == n:
return
print_subset_sum(i + 1, n, _set, target_sum, subset)
if _set[i] <= target_sum:
subset.append(_set[i])
print_subset_sum(i + 1, n, _set, target_sum - _set[i], subset)
subset.pop()
if __name__ == "__main__":
set_1 = [1, 2, 1]
sum_1 = 3
n_1 = len(set_1)
subset_1 = []
print("Output 1:")
print_subset_sum(0, n_1, set_1, sum_1, subset_1)
print()
flag = False
set_2 = [3, 34, 4, 12, 5, 2]
sum_2 = 30
n_2 = len(set_2)
subset_2 = []
print("Output 2:")
print_subset_sum(0, n_2, set_2, sum_2, subset_2)
if not flag:
print("There is no such subset")
OUTPUT
Output 1:
[21][12]
Output 2:
There is no such subset

RESULT:
Thus the above program has been executed successfully and the required output is displayed.
Exp No: 9
BRANCH AND BOUND - ASSIGNMENT PROBLEM
Date:

AIM

To write a python program to Branch and Bound - Assignment problem

ALGORITHM

Step 1: Start the program.


Step 2: Now considering our journey starting at city 1, visit other cities once and return to city 1.
Step 3: S is the subset of cities. According to our algorithm, for all |S| > 1, we will set the
distance cost(i, S, 1) = ∝. Here cost(i, S, j) means we are starting at city i, visiting the cities of S
once, and now we are at city j. We set this path cost as infinity because we do not know the
distance yet. So the values will be the following:

 Cost (2, {3, 4}, 1) = ∝ ; the notation denotes we are starting at city 2, going through
cities 3, 4, and reaching 1. And the path cost is infinity.

 cost(3, {2, 4}, 1) = ∝

 cost(4, {2, 3}, 1) = ∝

Step 4: Now, for all subsets of S, we need to find the following

 cost(i, S, j)=min cost (i, S−{i}, j)+dist(i,j), where j∈S and i≠j

Step 5: Stop the program.


PROGRAM
import math
maxsize = float('inf')
def copyToFinal(curr_path):
final_path[:N + 1] = curr_path[:]
final_path[N] = curr_path[0]
def firstMin(adj, i):
min = maxsize
for k in range(N):
if adj[i][k] < min and i != k:
min = adj[i][k]
return min
def secondMin(adj, i):
first, second = maxsize, maxsize
for j in range(N):
if i == j:
continue
if adj[i][j] <= first:
second = first
first = adj[i][j]

elif(adj[i][j] <= second and


adj[i][j] != first):
second = adj[i][j]
return second
def TSPRec(adj, curr_bound, curr_weight,
level, curr_path, visited):
global final_res
if level == N:
if adj[curr_path[level - 1]][curr_path[0]] != 0:

curr_res = curr_weight + adj[curr_path[level - 1]]\


[curr_path[0]]
if curr_res < final_res:
copyToFinal(curr_path)
final_res = curr_res
return

for i in range(N):

if (adj[curr_path[level-1]][i] != 0 and
visited[i] == False):
temp = curr_bound
curr_weight += adj[curr_path[level - 1]][i]

if level == 1:
curr_bound -= ((firstMin(adj, curr_path[level - 1]) +
firstMin(adj, i)) / 2)
else:
curr_bound -= ((secondMin(adj, curr_path[level - 1]) +
firstMin(adj, i)) / 2)
if curr_bound + curr_weight < final_res:
curr_path[level] = i
visited[i] = True
TSPRec(adj, curr_bound, curr_weight,
level + 1, curr_path, visited)
curr_weight -= adj[curr_path[level - 1]][i]
curr_bound = temp
visited = [False] * len(visited)
for j in range(level):
if curr_path[j] != -1:
visited[curr_path[j]] = True
def TSP(adj):
curr_bound = 0
curr_path = [-1] * (N + 1)
visited = [False] * N
for i in range(N):
curr_bound += (firstMin(adj, i) +
secondMin(adj, i))
curr_bound = math.ceil(curr_bound / 2)
visited[0] = True
curr_path[0] = 0
TSPRec(adj, curr_bound, 0, 1, curr_path, visited)

adj = [[0, 10, 15, 20],


[10, 0, 35, 25],
[15, 35, 0, 30],
[20, 25, 30, 0]]
N=4
final_path = [None] * (N + 1)
visited = [False] * N
final_res = maxsize
TSP(adj)
print("Minimum cost :", final_res)
print("Path Taken : ", end = ' ')
for i in range(N + 1):
print(final_path[i], end = ' ')
OUTPUT
Minimum cost : 80
Path Taken : 0 1 3 2 0

RESULT:
Thus the above program has been executed successfully and the required output is displayed.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy