TSP Using Bfs and Dfs
TSP Using Bfs and Dfs
a. Using BFS
AIM:
ALGORITHM:
OUTPUT:
PROGRAM:
from collections import deque
import itertools
def traveling_salesman_bfs(dist):
n = len(dist)
all_cities = list(range(n))
queue = deque()
for i in range(n):
queue.append((i, [i]))
min_length = float('inf')
best_path = []
while queue:
current_city, path = queue.popleft()
if len(path) == n:
length = calculate_path_length(path, dist)
if length < min_length:
min_length = length
best_path = path
continue
RESULT:
b.Using DSF
AIM:
ALGORITHM:
OUTPUT:
PROGRAM:
def calculate_path_length(path, dist):
length = 0
for i in range(len(path) - 1):
length += dist[path[i]][path[i + 1]]
length += dist[path[-1]][path[0]]
return length
if len(path) == n:
visited[next_city] = True
path.append(next_city)
visited[start_city] = True
dfs_tsp(dist, start_city, [start_city], visited, best_path, min_length)
visited[start_city] = False
return best_path, min_length[0]
if _name_ == "_main_":
dist = [
[0, 25, 10, 15],
[25, 0, 10, 45],
[10, 10, 0, 5],
[15, 45, 5, 0]
]
best_path, min_length = traveling_salesman_dfs(dist)
print("Optimal Path : ", best_path)
print("Minimum Length Using DFS: ", min_length)
RESULT: