DAA summarized unit 4
DAA summarized unit 4
return dp[n][capacity]
# Example Usage
weights = [1, 3, 4, 5]
values = [1, 4, 5, 7]
capacity = 7
print("Maximum value in Knapsack:", knapsack(weights, values, capacity))
for i in range(V):
for j in range(V):
dist[i][j] = graph[i][j]
for k in range(V):
for i in range(V):
for j in range(V):
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
return dist
# Example Usage
graph = [
[0, 3, float('inf'), 7],
[8, 0, 2, float('inf')],
[5, float('inf'), 0, 1],
[2, float('inf'), float('inf'), 0]
]
result = floyd_warshall(graph)
print("Shortest distances matrix:")
for row in result:
print(row)
Backtracking
Backtracking is a method for finding all solutions to problems by exploring all
possible options systematically.
1. N-Queens Problem
• Problem: Place N queens on an N x N chessboard such that no two
queens attack each other.
Code Implementation
python
CopyEdit
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), range(col, -1, -1)):
if board[i][j] == 1:
return False
return True
for i in range(n):
if is_safe(board, i, col, n):
board[i][col] = 1
if solve_n_queens(board, col + 1, n):
return True
board[i][col] = 0
return False
def n_queens(n):
board = [[0] * n for _ in range(n)]
if not solve_n_queens(board, 0, n):
return "No solution exists"
return board
# Example Usage
n=4
solution = n_queens(n)
for row in solution:
print(row)
for i in range(n):
if not visited[i] and graph[curr_pos][i]:
visited[i] = True
tsp_branch_and_bound(graph, i, n, visited, count + 1, cost +
graph[curr_pos][i], min_cost)
visited[i] = False
def travelling_salesman(graph):
n = len(graph)
visited = [False] * n
visited[0] = True
min_cost = [sys.maxsize]
tsp_branch_and_bound(graph, 0, n, visited, 1, 0, min_cost)
return min_cost[0]
# Example Usage
graph = [
[0, 10, 15, 20],
[10, 0, 35, 25],
[15, 35, 0, 30],
[20, 25, 30, 0]
]
print("Minimum cost for TSP:", travelling_salesman(graph))
Graph Coloring
Graph Coloring is another example of backtracking where you assign colors to
vertices such that no two adjacent vertices share the same color.
Code Implementation
python
CopyEdit
def is_valid(graph, color, vertex, c):
for i in range(len(graph)):
if graph[vertex][i] == 1 and color[i] == c:
return False
return True
return False