0% found this document useful (0 votes)
6 views

DAA summarized unit 4

The document discusses various algorithmic techniques including Dynamic Programming, Backtracking, and Branch and Bound, with a focus on specific problems like the Knapsack Problem, All-Pair Shortest Paths, N-Queens Problem, Travelling Salesman Problem, and Graph Coloring. Each section includes a problem statement and Python code implementations to solve the respective problems. The document serves as a guide for understanding these algorithms and their applications in optimization and problem-solving.

Uploaded by

risu.22128
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

DAA summarized unit 4

The document discusses various algorithmic techniques including Dynamic Programming, Backtracking, and Branch and Bound, with a focus on specific problems like the Knapsack Problem, All-Pair Shortest Paths, N-Queens Problem, Travelling Salesman Problem, and Graph Coloring. Each section includes a problem statement and Python code implementations to solve the respective problems. The document serves as a guide for understanding these algorithms and their applications in optimization and problem-solving.

Uploaded by

risu.22128
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Dynamic Programming

Dynamic Programming (DP) is a method for solving problems by breaking them


down into smaller subproblems, solving each subproblem just once, and
storing the results for future reference (memoization).
1. Knapsack Problem
The Knapsack Problem is a classic DP problem where you maximize the total
value of items that can be put into a knapsack of given capacity.
• Problem Statement: Given weights and values of n items, and a
knapsack capacity W, find the maximum value that can fit into the
knapsack.
Code Implementation
python
CopyEdit
def knapsack(weights, values, capacity):
n = len(values)
dp = [[0] * (capacity + 1) for _ in range(n + 1)]

for i in range(1, n + 1):


for w in range(1, capacity + 1):
if weights[i - 1] <= w:
dp[i][w] = max(dp[i - 1][w], values[i - 1] + dp[i - 1][w - weights[i - 1]])
else:
dp[i][w] = dp[i - 1][w]

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))

2. All-Pair Shortest Paths


Dynamic Programming is used in graph algorithms like Floyd-Warshall to find
the shortest paths between all pairs of nodes in a weighted graph.
Floyd-Warshall Algorithm
• Problem: Given a weighted graph (with possible negative weights but no
negative weight cycles), find the shortest distance between every pair of
vertices.
Code Implementation
python
CopyEdit
def floyd_warshall(graph):
V = len(graph)
dist = [[float('inf')] * V for _ in range(V)]

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

def solve_n_queens(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(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)

Branch and Bound


Branch and Bound is an optimization technique that reduces the search space
systematically and uses bounds to prune branches that cannot lead to an
optimal solution.
1. Travelling Salesman Problem (TSP)
• Problem: Given a set of cities and distances between them, find the
shortest route that visits each city exactly once and returns to the
starting city.
Code Implementation
python
CopyEdit
import sys

def tsp_branch_and_bound(graph, curr_pos, n, visited, count, cost, min_cost):


if count == n and graph[curr_pos][0]:
min_cost[0] = min(min_cost[0], cost + graph[curr_pos][0])
return

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

def graph_coloring_util(graph, m, color, vertex):


if vertex == len(graph):
return True

for c in range(1, m + 1):


if is_valid(graph, color, vertex, c):
color[vertex] = c
if graph_coloring_util(graph, m, color, vertex + 1):
return True
color[vertex] = 0

return False

def graph_coloring(graph, m):


color = [0] * len(graph)
if not graph_coloring_util(graph, m, color, 0):
return "No solution exists"
return color
# Example Usage
graph = [
[0, 1, 1, 1],
[1, 0, 1, 0],
[1, 1, 0, 1],
[1, 0, 1, 0]
]
m=3
print("Color assignment:", graph_coloring(graph, m))

You might also like