DAA RECORD 6 TO 9
DAA RECORD 6 TO 9
DIJKSTRA’S ALGORITHM
PROGRAM:
import heapq
while pq:
# Get the node with the smallest distance
current_distance, current_node = heapq.heappop(pq)
# If the current distance is greater than the recorded distance, skip processing
if current_distance > distances[current_node]:
continue
# If a shorter path to the neighbor is found, update the distance and add to queue
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(pq, (distance, neighbor))
return distances
# Get the edges from the user (format: node1 node2 weight)
for _ in range(num_edges):
u, v, w = map(int, input("Enter edge (u, v, weight): ").split())
graph[u].append((v, w))
graph[v].append((u, w)) # Assuming an undirected graph
if __name__ == "__main__":
main()
OUTPUT:
PROGRAM:
import heapq
# The root of the tree is the only remaining node in the heap
return heap[0]
return ''.join(decoded_text)
if __name__ == "__main__":
main()
OUTPUT:
PROGRAM:
import numpy as np
while True:
if np.all(tableau[-1, :-1] >= 0):
return tableau[:-1, -1], tableau[-1, -1]
for i in range(len(tableau)):
if i != pivot_row:
tableau[i] -= tableau[i, pivot_col] * tableau[pivot_row]
def main():
num_variables = int(input("Enter the number of variables: "))
num_constraints = int(input("Enter the number of constraints: "))
A = []
for _ in range(num_constraints):
A.append(list(map(float, input(f"Enter the coefficients for constraint {_ + 1}: ").split())))
if __name__ == "__main__":
main()
OUTPUT:
PROGRAM:
res = False
for col in range(n):
if is_safe(board, row, col, n):
board[row] = col
res = solve_nqueens(board, row + 1, n) or res
board[row] = -1 # Backtrack
return res
def main():
n = int(input("Enter the number of queens (N): "))
board = [-1] * n
if not solve_nqueens(board, 0, n):
print("Solution does not exist")
if __name__ == "__main__":
main()
OUTPUT:
.Q..
...Q
Q...
..Q.
8(B)-BACKTRACKING-SUBSET SUM PROBLEM
PROGRAM:
return False
def main():
arr = list(map(int, input("Enter the array of numbers: ").split()))
target = int(input("Enter the target sum: "))
if not subset_sum(arr, target):
print("No subset found with the given sum.")
if __name__ == "__main__":
main()
OUTPUT:
PROGRAM:
import numpy as np
import heapq
class Node:
def __init__(self, level, cost_matrix, assigned, cost, bound):
self.level = level
self.cost_matrix = cost_matrix
self.assigned = assigned
self.cost = cost
self.bound = bound
# The lower bound is the sum of the row and column reductions
row_reduction_sum = np.sum(row_min)
col_reduction_sum = np.sum(col_min)
heapq.heappush(queue, root)
while queue:
node = heapq.heappop(queue)
# If the lower bound is greater than the best solution found so far, prune the branch
if node.bound >= best_cost:
continue
# If we have assigned all tasks (level == n-1), check if we have a better solution
if node.level == n - 1:
if node.cost < best_cost:
best_cost = node.cost
best_assignment = node.assigned.copy()
continue
# Generate the next level nodes (assign the next task to a worker)
level = node.level + 1
for j in range(n):
if node.assigned[j] == -1: # If worker j is not yet assigned
new_assigned = node.assigned.copy()
new_assigned[j] = level
def main():
# Read the input for the Assignment Problem
n = int(input("Enter the number of workers/tasks (n): "))
print("Enter the cost matrix:")
cost_matrix = []
for _ in range(n):
OUTPUT:
PROGRAM:
import numpy as np
import heapq
class Node:
def __init__(self, level, cost, path, bound):
self.level = level # Current level (number of cities visited)
self.cost = cost # Total cost of the path so far
self.path = path # List of cities visited so far
self.bound = bound # Lower bound for this node
best_cost = float('inf')
best_path = None
while min_heap:
# Get the node with the smallest bound (best possible solution so far)
node = heapq.heappop(min_heap)
# If the bound is greater than the best cost, prune this branch
if node.bound >= best_cost:
continue
if __name__ == "__main__":
main()
OUTPUT: