0% found this document useful (0 votes)
22 views47 pages

Daa Record Ai

Uploaded by

sfstan.prince
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views47 pages

Daa Record Ai

Uploaded by

sfstan.prince
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

EXP NO: 1(a) IMPLEMENT RECURSIVE ALGORITHM

DATE:

AIM:
To Implement a python program for recursive algorithm.

PROCEDURE:
(FACTORIAL)

STEP 1: start

STEP 2: Read number n

STEP 3: Call factorial(n)

STEP 4: Print factorial(n)

STEP 5: Stop

Factorial(n)

STEP 1: If n==1 return 1

STEP 2: Else

Fact=n=factorial(n-1)

STEP 3: Return Fact

1
PROGRAM

def factorial(n):
if n<=1:
return 1
else:
return n*factorial(n-1)
num = 5;
print("Factorial of",num,"is",factorial(num))

2
OUTPUT:

Factorial of 5 is 20

RESULT

Thus the program for recursive algorithm was executed successfully

3
EXP NO: 1 (b) IMPLEMENT NON- RECURSIVE ALGORITHM

DATE:

AIM:
To Implement a python program for Non-Recursive algorithm.

PROCEDURE:

STEP 1: set beg = lower_bound, end = upper_bound, pos = - 1

STEP 2: repeat steps 3 and 4 while beg <=end

STEP 3: set mid = (beg + end)/2

STEP 4: if a[mid] = val

set pos = mid

print pos

go to step 6

else if a[mid] > val

set end = mid - 1

else

set beg = mid + 1

STEP 5: if pos = -1

print "value is not present in the array"

STEP 6: exit.

4
PROGRAM

def binarySearch(arr, l, r, x):

if r >= l:

mid = l + (r - l) // 2

if arr[mid] == x:
return mid

elif arr[mid] > x:


return binarySearch(arr, l, mid-1, x)

else:
return binarySearch(arr, mid + 1, r, x)

else:
return -1

arr = [2, 3, 4, 10, 40]


x = 10

result = binarySearch(arr, 0, len(arr)-1, x)

if result != -1:
print("Element is present at index % d" % result)
else:

print("Element is not present in array")

5
OUTPUT

Element is present at index 3

RESULT

Thus the program for Non recursive was executed successfully

6
EXP NO:2 DECREASE AND CONQUER - TOPOLOGICAL SORTING

DATE:

AIM:

To implement an algorithm for Topological Sorting, a linear ordering of vertices in a


directed acyclic graph (DAG), using the Decrease and Conquer strategy.

PROCEDURE:

STEP 1: Start

STEP 2: Find a vertex that has indegree = 0 (no incoming edges)

STEP 3: Remove all the edges from that vertex that go outward

(make it's outdegree= 0 remove outgoing edges)

STEP 4: Add that vertex to the array representing topological sorting of the graph.

STEP 5: Repeat till there are no more vertices left.

STEP 6: Stop.

7
PROGRAM

from collections import defaultdict

class Graph:
def __init__(self, vertices):
self.graph = defaultdict(list)
self.V = vertices

def add_edge(self, u, v):


self.graph[u].append(v)

def topological_sort_util(self, v, visited, stack):


visited[v] = True

for neighbor in self.graph[v]:


if not visited[neighbor]:
self.topological_sort_util(neighbor, visited, stack)

stack.append(v)

def topological_sort(self):
visited = [False] * self.V
stack = []

for i in range(self.V):
if not visited[i]:
self.topological_sort_util(i, visited, stack)

return stack[::-1]

# Example Usage:
g = Graph(6)
8
g.add_edge(5, 2)
g.add_edge(5, 0)
g.add_edge(4, 0)
g.add_edge(4, 1)
g.add_edge(2, 3)
g.add_edge(3, 1)

print("Following is a Topological Sort of the given graph")


result = g.topological_sort()
print(result)

9
OUTPUT

Following is a Topological Sort of the given graph

[5, 4, 2, 3, 1, 0]

RESULT

Thus the program for Topological Sorting was executed successfully

10
EXP NO:3 TRANSFORM AND CONQUER - HEAP SORT

DATE:

AIM:
To implement the heap sort algorithm using a Transform and Conquer approach.

PROCEDURE:

STEP 1: Build a max heap from the input data.

STEP 2: At this point, the maximum element is stored at the root of the heap.

Replace it with the last item of the heap followed by reducing the size of the

heap by 1. Finally, heapify the root of the tree.

STEP 3: Repeat step 2 while the size of the heap is greater than 1.

11
PROGRAM
def heapify(arr, n, i):
largest = i
left_child = 2 * i + 1
right_child = 2 * i + 2

if left_child < n and arr[left_child] > arr[largest]:


largest = left_child

if right_child < n and arr[right_child] > arr[largest]:


largest = right_child

if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
heapify(arr, n, largest)

def heap_sort(arr):
n = len(arr)

# Build a max heap


for i in range(n // 2 - 1, -1, -1):
heapify(arr, n, i)

# Extract elements one by one


for i in range(n - 1, 0, -1):
arr[i], arr[0] = arr[0], arr[i] # Swap the root (maximum element) with the last
element
heapify(arr, i, 0) # Heapify the reduced heap

# Example Usage:
arr = [12, 11, 13, 5, 6, 7]
print("Original array:", arr)
heap_sort(arr)
print("Sorted array:", arr)
12
OUTPUT

Original array: [12, 11, 13, 5, 6, 7]


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

RESULT

Thus the program for Heap Sort was executed successfully

13
EXP NO:4 DYNAMIC PROGRAMMING – COIN CHANGE PROBLEM

DATE:

AIM:
To implement Coin change problem using Dynamic programming.

PROCEDURE:

STEP 1: Start.

STEP 2: Get input amount as a amt.

STEP 3: if amount = 0, then return 0.

STEP 4: if minimum of coins array > amount, then return -1.

STEP 5: Define one array called dp, of size amount + 1, and fill this with -1.

STEP 6: for i in range coins array. if i > length of dp – 1, then skip the next part, go
for the next iteration. dp[i] := 1.

STEP 7: Return dp[amount].

STEP 8: Stop

14
PROGRAM

class Solution(object):

def coinChange(self, coins, amount):

if amount == 0 :

return 0

if min(coins) > amount:

return -1

dp = [-1 for i in range(0, amount + 1)]

for i in coins:

if i > len(dp) - 1:

continue

dp[i] = 1

for j in range(i + 1, amount + 1):

if dp[j - i] == -1:

continue

elif dp[j] == -1:

dp[j] = dp[j - i] + 1

else:

dp[j] = min(dp[j], dp[j - i] + 1)

return dp[amount]

ob1 = Solution()

amt=int(input("Enter the amount:"))

15
print(ob1.coinChange([1,2,5],amt))

OUTPUT

Enter the amount: 12

RESULT

Thus the program for Coin changing problem was executed successfully

16
EXP NO:5 DYNAMIC PROGRAMMING – FLOYD-WARSHALL

DATE:

AIM:
To implement Floyd-Warshall Algorithm algorithm using Dynamic programming.

PROCEDURE:

STEP 1: Start

STEP 2: Get input ‘n’ where n = no of vertices

STEP 3: Assign A = matrix of dimension n*n

STEP 4: for k = 1 to n

STEP 5: for i = 1 to n

STEP 6: for j = 1 to n

STEP 7: Ak[i, j] = min (Ak-1[i, j], Ak-1[i, k] + Ak-1[k, j])

STEP 8: Return A

STEP 9: Stop

17
PROGRAM

def floyd_warshall(graph):
n = len(graph)
# Initialize the distance matrix with the graph's adjacency matrix
dist = [row[:] for row in graph]

# Calculate the shortest paths


for k in range(n):
for i in range(n):
for j in range(n):
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])

return dist

# Example Usage:
# Here, 'inf' represents infinity or unreachability, and 0 represents no distance (vertex
to itself).
graph = [
[0, 1, float('inf'), 1],
[1, 0, 1, float('inf')],
[float('inf'), 1, 0, 1],
[1, float('inf'), 1, 0]
]

result = floyd_warshall(graph)

# Print the transitive closure (shortest paths) matrix


for row in result:
print(row)

18
OUTPUT

[0, 1, 2, 1]
[1, 0, 1, 2]
[2, 1, 0, 1]
[1, 2, 1, 0]

RESULT

Thus the program for Floyd Warshall was executed successfully

19
EXP NO:6 DYNAMIC PROGRAMMING – KNAPSACK PROBLEM
DATE:

AIM:
To implement Knapsack problem using Dynamic programming.

PROCEDURE:

STEP 1: Start

STEP 2: Calculate the ratio(value/weight) for each item.

STEP 3: Sort all the items in decreasing order of the ratio.

STEP 4: Initialize res =0

STEP 5: Do the following for every item “i” in the sorted order.

STEP 6: If the weight of the current item is less than or equal to the remaining
capacity then add the value of that item into the result.

STEP 7: Else add the current item as much as we can and break out of the loop.

STEP 8: Return res.

STEP 9: Stop

20
PROGRAM

def knapSack(W, wt, val, n):

K = [[0 for x in range(W + 1)] for x in range(n + 1)]

# Build table K[][] in bottom up manner

for i in range(n + 1):

for w in range(W + 1):

if i == 0 or w == 0:

K[i][w] = 0

elif wt[i-1] <= w:

K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w])

else:

K[i][w] = K[i-1][w]

return K[n][W]

# Driver program to test above function

val = [60, 100, 120]

wt = [10, 20, 30]

W = 50

n = len(val)

print(knapSack(W, wt, val, n))

21
OUTPUT

220

RESULT

Thus the program for Knapsack was executed successfully

22
EXP NO:7 GREEDY TECHNIQUE – DIJKSTRA’S ALGORITHM

DATE:

AIM:
To develop a program to find the shortest paths to other vertices using Djikstra’s
algorithm for the given vertex in a weighted connected graph.

PROCEDURE:

STEP 1: Start

STEP 2: Create a set that keeps track of vertices included in the shortest-path tree.

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 a set doesn’t include all vertices, pick a vertex u which is not there in and

has a minimum distance.

STEP 5: Include u to Set.

STEP 6: Then update distance value of all adjacent vertices of u.

STEP 7: To update the distance values, iterate through all adjacent vertices.

STEP 8: For every adjacent vertex v, if 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 9: Stop

23
PROGRAM

import heapq

def dijkstra(graph, start):


# Initialize distances with infinity and set distance for the start node to 0
distances = {vertex: float('infinity') for vertex in graph}
distances[start] = 0

# Priority queue to keep track of vertices with their current distances


priority_queue = [(0, start)]

while priority_queue:
current_distance, current_vertex = heapq.heappop(priority_queue)

# If the current distance is greater than the known distance, skip


if current_distance > distances[current_vertex]:
continue

# Explore neighbors and update distances


for neighbor, weight in graph[current_vertex].items():
distance = current_distance + weight

# If the new distance is shorter, update the distance and enqueue the neighbor
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(priority_queue, (distance, neighbor))
return distances

24
# Example Usage:
graph = {
'A': {'B': 1, 'C': 4},
'B': {'A': 1, 'C': 2, 'D': 5},
'C': {'A': 4, 'B': 2, 'D': 1},
'D': {'B': 5, 'C': 1}
}

start_node = 'A'
shortest_distances = dijkstra(graph, start_node)
print(f"Shortest distances from node {start_node}: {shortest_distances}")

25
OUTPUT

Shortest distances from node A: {'A': 0, 'B': 1, 'C': 3, 'D': 4}

RESULT

Thus the program for Dijkstras algorithm was executed successfully

26
EXP NO:8 GREEDY TECHNIQUE – HUFFMAN TREES AND CODES

DATE:

AIM:
To implement Huffman Trees and Codes using Greedy technique.

PROCEDURE:

STEP 1: Start

STEP 2: Input is an array of unique characters along with their frequency of occurrences

STEP 3: 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 4: Extract two nodes with the minimum frequency from the min heap.

STEP 6: Create a new internal node with a frequency equal to the sum of the two node

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 7: Repeat steps 2 and 3 until the heap contains only one node. The remaining node is

the root node, and the tree is complete.

STEP 8: Stop.

27
PROGRAM

import heapq
from collections import Counter

class HuffmanNode:
def __init__(self, char, freq):
self.char = char
self.freq = freq
self.left = None
self.right = None

def __lt__(self, other):


return self.freq < other.freq

def build_huffman_tree(data):
frequency = Counter(data)
heap = [HuffmanNode(char, freq) for char, freq in frequency.items()]
heapq.heapify(heap)

while len(heap) > 1:


left = heapq.heappop(heap)
right = heapq.heappop(heap)

internal_node = HuffmanNode(None, left.freq + right.freq)


internal_node.left, internal_node.right = left, right

heapq.heappush(heap, internal_node)

return heap[0]

def build_huffman_codes(root, current_code="", codes=None):


28
if codes is None:
codes = {}

if root is not None:


if root.char is not None:
codes[root.char] = current_code
build_huffman_codes(root.left, current_code + "0", codes)
build_huffman_codes(root.right, current_code + "1", codes)

def huffman_encode(data, codes):


encoded_data = ''.join(codes[char] for char in data)
return encoded_data

def huffman_decode(encoded_data, root):


current_node = root
decoded_data = ""

for bit in encoded_data:


if bit == '0':
current_node = current_node.left
else:
current_node = current_node.right

if current_node.char is not None:


decoded_data += current_node.char
current_node = root

return decoded_data

# Example Usage:
data = "ABRACADABRA"
root = build_huffman_tree(data)
codes = {}
29
build_huffman_codes(root, "", codes)
encoded_data = huffman_encode(data, codes)
decoded_data = huffman_decode(encoded_data, root)

print("Original Data:", data)


print("Encoded Data:", encoded_data)
print("Decoded Data:", decoded_data)
print("\nHuffman Codes:")
for char, code in codes.items():
print(f"{char}: {code}")

30
OUTPUT

Original Data: ABRACADABRA


Encoded Data: 0100110111101100100110
Decoded Data: ABRACADABRA

Huffman Codes:
A: 0
B: 10
R: 110
C: 1110
D: 1111

RESULT

Thus the program for Huffman trees and codes was executed successfully

31
EXP NO:9 BACKTRACKING – N-QUEEN PROBLEM

DATE:

AIM:
To implement N-Queen Problem usimg Backtracking.

PROCEDURE:

STEP 1: Start in the leftmost column.

STEP 2: If all queens are placed return true.

STEP 3: Try all rows in the current column.

Do following for every tried row.

a) If the queen can be placed safely in this row, then mark this [row, column] as part of the

solution and recursively check if placing queen here leads to a solution.

b) If placing the queen in [row, column] leads to a solution then return true.

c) If placing queen doesn't lead to a solution then unmark this [row, column] (Backtrack)

and go to step (a) to try other rows.

STEP 4: If all rows have been tried and nothing worked, return false to trigger backtracking.

32
PROGRAM

def is_safe(board, row, col, n):


# Check if there is a queen in the same row on the left side
for i in range(col):
if board[row][i] == 1:
return False

# Check upper diagonal on the left side


for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
if board[i][j] == 1:
return False

# Check lower diagonal on the left side


for i, j in zip(range(row, n, 1), range(col, -1, -1)):
if board[i][j] == 1:
return False

return True

def solve_nqueens_util(board, col, n, solutions):


if col == n:
# All queens are placed successfully
solutions.append(["".join(["Q" if cell == 1 else "." for cell in row]) for row in
board])
return

for i in range(n):
if is_safe(board, i, col, n):
board[i][col] = 1

solve_nqueens_util(board, col + 1, n, solutions)

33
# Backtrack: Remove the queen if the placement doesn't lead to a solution
board[i][col] = 0

def solve_nqueens(n):
board = [[0] * n for _ in range(n)]
solutions = []
solve_nqueens_util(board, 0, n, solutions)
return solutions

# Example Usage:
n=4
solutions = solve_nqueens(n)

for idx, solution in enumerate(solutions, start=1):


print(f"Solution {idx}:")
for row in solution:
print(row)
print()

34
OUTPUT

Solution 1:
.Q..
...Q
Q...
..Q.

Solution 2:
..Q.
Q...
...Q
.Q..

RESULT

Thus the program for N Queens problem was executed successfully

35
EXP NO:10 BACKTRACKING – SUBSET SUM PROBLEM

DATE:

AIM:
To implement Subset Sum Problem using backtracking.

PROCEDURE:

STEP 1: Start with an empty set.

STEP 2: Add the next element from the list to the set.

STEP 3: If the subset is having sum M, then stop with that subset as solution.

STEP 4: If the subset is not feasible or if we have reached the end of the set, then backtrack

through the subset until we find the most suitable value.

STEP 5: If the subset is feasible (sum of subset < M) then go to step 2.

STEP 6: If we have visited all the elements without finding a suitable subset and if no

backtracking is possible then stop without solution.

36
PROGRAM

def is_subset_sum(nums, n, target_sum, current_sum, selected, solutions):


if current_sum == target_sum:
solutions.append(selected.copy())
return

if n == 0 or current_sum > target_sum:


return

# Include the current element in the subset


selected.append(nums[n - 1])
is_subset_sum(nums, n - 1, target_sum, current_sum + nums[n - 1], selected,
solutions)

# Exclude the current element from the subset


selected.pop()
is_subset_sum(nums, n - 1, target_sum, current_sum, selected, solutions)

def subset_sum(nums, target_sum):


solutions = []
is_subset_sum(nums, len(nums), target_sum, 0, [], solutions)
return solutions

# Example Usage:
nums = [2, 3, 7, 8, 10]
target_sum = 10
solutions = subset_sum(nums, target_sum)
print(f"Original Set: {nums}")
print(f"Target Sum: {target_sum}")
print("Subset Sums:")
for solution in solutions:

37
print(solution)

OUTPUT

Original Set: [2, 3, 7, 8, 10]


Target Sum: 10
Subset Sums:
[10]
[8, 2]
[7, 3]

RESULT

Thus the program Subset sum problem was executed successfully

38
EXP NO:11 BRANCH AND BOUND - ASSIGNMENT PROBLEM

DATE:

AIM:
To implement Assignment Problem using Branch and Bound technique.

PROCEDURE:

STEP 1: Start
STEP 2: Get the input data.
STEP 3: Constraints:
a) Each worker is assigned to at most 1 task.
b) Each task is assigned to exactly one worker.
STEP 4: Solve the problem.
STEP 5: Print the solution.

39
PROGRAM

import numpy as np

class AssignmentProblem:
def __init__(self, cost_matrix):
self.cost_matrix = np.array(cost_matrix)
self.n = len(cost_matrix)
self.row_reduction()
self.column_reduction()
self.marked_rows = [False] * self.n
self.marked_columns = [False] * self.n
self.assignment = [-1] * self.n
self.total_cost = 0

def row_reduction(self):
for i in range(self.n):
min_val = min(self.cost_matrix[i])
self.cost_matrix[i] -= min_val

def column_reduction(self):
for j in range(self.n):
min_val = min(self.cost_matrix[:, j])
self.cost_matrix[:, j] -= min_val

def find_minimal_zeros(self):
min_val = float('inf')
for i in range(self.n):
for j in range(self.n):
if not self.marked_rows[i] and not self.marked_columns[j]:
if self.cost_matrix[i, j] == 0 and min_val > 0:
min_val = self.cost_matrix[i, j]
min_zero_position = (i, j)
return min_zero_position if min_val < float('inf') else None

40
def mark_zeros(self, row, col):
for i in range(self.n):
if self.cost_matrix[i, col] == 0:
self.marked_rows[i] = True
for j in range(self.n):
if self.cost_matrix[row, j] == 0:
self.marked_columns[j] = True

def unmark_all(self):
self.marked_rows = [False] * self.n
self.marked_columns = [False] * self.n

def assign_job(self, row, col):


self.assignment[row] = col
self.marked_rows[row] = True
self.marked_columns[col] = True

def find_optimal_assignment(self):
while None in self.assignment:
zero_position = self.find_minimal_zeros()
if zero_position is None:
break
row, col = zero_position
self.assign_job(row, col)
self.row_reduction()
self.column_reduction()
self.unmark_all()

for i in range(self.n):
self.total_cost += self.cost_matrix[i, self.assignment[i]]

return self.assignment, self.total_cost

# Example Usage:
cost_matrix = [
41
[9, 11, 14, 11],
[6, 15, 13, 13],
[12, 13, 5, 6],
[5, 6, 9, 10]
]

assignment_problem = AssignmentProblem(cost_matrix)
assignment, total_cost = assignment_problem.find_optimal_assignment()

print("Optimal Assignment:", assignment)


print("Total Cost:", total_cost)

42
OUTPUT

Optimal Assignment: [-1, -1, -1, -1]


Total Cost: 11

RESULT

Thus the program for Assignment problem was executed successfully

43
EXP NO:12 BRANCH AND BOUND - TRAVELING SALESMAN PROBLEM

DATE:

AIM:
To implement Travelling Salesman Problem using Branch and Bound technique.

PROCEDURE:

STEP 1: Initially, graph is represented by cost matrix C, where


Cij = cost of edge, if there is a direct path from city i to city j
Cij = ∞, if there is no direct path from city i to city j.
STEP 2: Convert cost matrix to reduced matrix by subtracting minimum values from
appropriate rows and columns, such that each row and column contain at least one zero
entry.
STEP 3: Find cost of reduced matrix. Cost is given by summation of subtracted amount
from the cost matrix to convert it in to reduce matrix.

STEP 4: Prepare state space tree for the reduce matrix.


STEP 5: Find least cost valued node A (i.e. E-node), by computing reduced cost node
matrix.
with every remaining node.
STEP 6: If <i, j> edge is to be included, then do following:
(a) Set all values in row i and all values in column j of A to ∞
(b) Set A[j, 1] = ∞
(c) Reduce A again, except rows and columns having all ∞ entries.
STEP 7: Compute the cost of newly created reduced matrix as,
Cost = L + Cost(i, j) + r
Where, L is cost of original reduced cost matrix and r is A[i, j].
STEP 8: If all nodes are not visited then go to step 4.

44
PROGRAM

import numpy as np

class TravelingSalesmanProblem:
def __init__(self, distance_matrix):
self.n = len(distance_matrix)
self.distance_matrix = np.array(distance_matrix)
self.visited = set()
self.best_path = None
self.best_cost = np.inf

def greedy_lower_bound(self, path, cost):


# Greedy approach to find a lower bound
unvisited_cities = set(range(self.n)) - set(path)
for city in unvisited_cities:
min_distance = np.min(self.distance_matrix[path[-1], list(unvisited_cities)])
cost += min_distance
path.append(city)
return path, cost

def backtrack(self, path, cost):


if len(path) == self.n:
# If all cities are visited, check if it forms a better solution
cost += self.distance_matrix[path[-1], path[0]]
if cost < self.best_cost:
self.best_path = path.copy()
self.best_cost = cost
else:
# Explore unvisited cities
unvisited_cities = set(range(self.n)) - set(path)
for city in unvisited_cities:
if cost + np.min(self.distance_matrix[path[-1], list(unvisited_cities)]) <
45
self.best_cost:
self.visited.add(city)
self.backtrack(path + [city], cost + self.distance_matrix[path[-1], city])
self.visited.remove(city)

def find_optimal_route(self):
# Start with the first city
initial_path = [0]
initial_cost = 0

# Use a greedy algorithm to find a lower bound


initial_path, initial_cost = self.greedy_lower_bound(initial_path, initial_cost)

# Start backtracking from the greedy solution


self.backtrack(initial_path, initial_cost)

return self.best_path, self.best_cost

# Example Usage:
distance_matrix = [
[np.inf, 2, 9, 10],
[1, np.inf, 6, 4],
[15, 7, np.inf, 8],
[6, 3, 12, np.inf]
]

tsp_problem = TravelingSalesmanProblem(distance_matrix)
optimal_route, optimal_cost = tsp_problem.find_optimal_route()
print("Optimal Route:", optimal_route)
print("Optimal Cost:", optimal_cost)

46
OUTPUT

Optimal Route: [0, 1, 3, 2, 0]


Optimal Cost: 23

RESULT
Thus the program for Travelling Salesman problem was executed successfully

47

You might also like