NEP -DAA -DESIGN AND ANALYSIS OF ALOGRITHM

PROGRAM 1 PROGRAM 2 PROGRAM 3 PROGRAM 4 PROGRAM 5 PROGRAM 6 PROGRAM 7 PROGRAM 8 PROGRAM 9 PROGRAM 10 PROGRAM 11 PROGRAM 12

PART B

PROGRAM B1 PROGRAM B2 PROGRAM B3 PROGRAM B4 PROGRAM B5 PROGRAM B6 PROGRAM B7 PROGRAM B8 . . .

 
   #2.Write a program to perform Travelling Salesman Problem

from itertools import permutations

 
def calculate_path_distance(graph, path):
    distance = 0
    for i in range(len(path) - 1):
        distance += graph[path[i]][path[i + 1]]
    distance += graph[path[-1]][path[0]]  
    return distance

def tsp_brute_force(graph):
    
    cities = list(range(len(graph)))
    min_distance = float("inf")
    best_path = None

   
    for path in permutations(cities):
        current_distance = calculate_path_distance(graph, path)
        if current_distance < min_distance:
            min_distance = current_distance
            best_path = path

    return best_path, min_distance

# Example usage
# Define the graph as an adjacency matrix (distance between cities)
graph = [
    [0, 29, 20, 21],
    [29, 0, 15, 17],
    [20, 15, 0, 28],
    [21, 17, 28, 0]
]

best_path, min_distance = tsp_brute_force(graph)
print("Best Path:", best_path)
print("Minimum Distance:", min_distance)