0% found this document useful (0 votes)
33 views5 pages

PB Daa

The document contains implementations of various algorithms including the N-Queens problem, subset sum problem, Prim's algorithm for minimum spanning tree, the traveling salesman problem, and the knapsack problem. Each algorithm is presented with Python code, input prompts, and explanations of their functionality. The document serves as a guide for solving these classic algorithmic problems using backtracking and dynamic programming techniques.
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)
33 views5 pages

PB Daa

The document contains implementations of various algorithms including the N-Queens problem, subset sum problem, Prim's algorithm for minimum spanning tree, the traveling salesman problem, and the knapsack problem. Each algorithm is presented with Python code, input prompts, and explanations of their functionality. The document serves as a guide for solving these classic algorithmic problems using backtracking and dynamic programming techniques.
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/ 5

1.

Write a program to implement backtracking algorithm for solving problems like N


queens.

def is_safe(board,row,col,n): 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 solve_n_queens(n):
board=[[ 0 for _ in range(n)]for _ in range(n)] if not
solve_n_queens_util(board,0,n):
print("too solution exists") return
print_solution(board)

def solve_n_queens_util(board,col,n):
if col>=n:
return True
for i in range(n):
if is_safe(board,i,col,n):
board[i][col]=1 if
solve_n_queens_util(board,col+1,n):
return True
board[i][col]=0
return False

def print_solution(board):
for row in board:
print(" ".join(map(str,row)))

n = int(input("Enter the board size : ")) solve_n_queens(n)


2. Design and implement in to 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}. Display a suitable message, if the given
problem instance doesn't have a solution.
def find_subset_with_sum(s,d):
def find_subset_recursive(index,current_sum,current_subset):
if current_sum==d:
subsets.append(list(current_subset))
return
if current_sum> d or index==len(s):
return
current_subset.add(s[index])
find_subset_recursive(index+1,current_sum+s[index],current_subset)
current_subset.remove(s[index])
find_subset_recursive(index+1,current_sum,current_subset)
subsets=[]
find_subset_recursive(0,0,set())
return subsets
n=int(input("Enter the size of the array:"))
arr=[0]*n
print("Enter the array elements:")
for i in range(n):
arr[i]=int(input())
d=int(input("Enter the target sum:"))
result=find_subset_with_sum(list(arr),d)
if result:
print("Subsets with sum",d,"found:")
for subset in result:
print(set(subset))
else:
print("No subset found")

3.Prim’s
def find_min_edge(matrix, Vt):
min_edge = None
min_weight= float('inf')
V = len(matrix)
for u in Vt:
for v in range (V):
if v not in Vt and matrix[u][v]> 0 and matrix[u][v] < min_weight:
min_edge=(u, v, matrix[u][v])
min_weight=matrix[u][v]
return min_edge, min_weight
def prim(matrix):
V=len(matrix)
start_vertex = 0
Vt={start_vertex}
Et=[]
total_weight=0
while len(Vt)<V:
min_edge,min_weight=find_min_edge(matrix, Vt)
if min_edge is None:
break
u, v, weight = min_edge
Vt.add(v)
Et.append((u, v, weight))
total_weight += weight
return Et, total_weight
no_vertices = int(input("Enter the number of vertices: "))
graph = []
print("Enter the weight adjacency Matrix:")
for i in range(no_vertices):
row = list(map(int,input(f"Enter weight of the vertex {i}:").split()))
graph.append(row)
minimum_spanning_tree, total_weight = prim(graph)
print("Minimum Spanning Tree:", minimum_spanning_tree)
print("Total Weight of MST:", total_weight)

4.travelling salesman
from itertools import permutations
def calculate_total_distance(path,distances):
total_distance=0
for i in range(len(path) - 1):
total_distance+= distances[path[i]][path[i +1]]
total_distance += distances[path[-1]][path[0]]
return total_distance
def travelling_salesman_bruteforce(distances):
num_cities =len(distances)
cities= list(range(num_cities))
shortest_path = None
min_distance=float('inf')
for path in permutations(cities):
current_distance = calculate_total_distance(path, distances)
if current_distance < min_distance:
min_distance=current_distance
shortest_path=path
return shortest_path, min_distance
distances =[
[1,2,5,7],
[2,0,3,9],
[5,3,0,6],
[7,9,6,0]
]
shortest_path, min_distance=travelling_salesman_bruteforce(distances)
print(f"shortest path: {shortest_path}")
print(f"minimum distance:{min_distance}")

5.Knapsak prblm
def knapsack_recursive(weights, values,capacity,n):
if capacity == 0 or n == 0:
return 0,[]
if weights[n-1]>capacity:
return knapsack_recursive(weights, values,capacity,n-1)
include_value,include_items=knapsack_recursive(weights, values,capacity - weights[n-1],n-1)
include_value+=values[n-1]
exclude_value, exclude_items=knapsack_recursive(weights,values,capacity,n-1)
if include_value>exclude_value:
return include_value,include_items+[n-1]
else:
return exclude_value,exclude_items
n=int(input("Enter the number of items:"))
weights=[]
values=[]
print("Enter weights:")
for i in range(n):
weights.append(int(input()))
print("Enter values")
for i in range(n):
values.append(int(input()))
capacity=int(input("Enter the capacity of the knapsack"))
optimal_value,optimal_items=knapsack_recursive(weights,values,capacity,n)
print("Optimal Value:",optimal_value)
print("Optimal Items(0-based indices):",optimal_items)

You might also like