You are on page 1of 2

Q)Traveling salesman problem in python with line by line explination.

A TSP tour in the


graph is 1-2-4-3-1. The cost of the tour is 10+25+30+15 which is 80. matrix
representation of graph

{ { 0, 10, 15, 20 },

{ 10, 0, 35, 25 },

{ 15, 35, 0, 30 },

{ 20, 25, 30, 0 } };

Code

import itertools

# Define the adjacency matrix to represent the distances between cities

distance_matrix = [

[0, 10, 15, 20],

[10, 0, 35, 25],

[15, 35, 0, 30],

[20, 25, 30, 0]

# Generate all possible permutations of cities to explore different routes

num_cities = len(distance_matrix)#4

cities = list(range(1, num_cities))

all_permutations = itertools.permutations(cities)

# Initialize variables to track the best route and its distance

best_route = None

best_distance = float("inf") #"inf" represents positive infinity

# Iterate through all permutations and calculate their total distance


for route in all_permutations:

total_distance = 0

current_city = 0 # Starting city is city 0

for next_city in route:

total_distance += distance_matrix[current_city][next_city]

current_city = next_city

# Add the distance to return to the starting city (city 0)

total_distance += distance_matrix[current_city][0]

# Update the best route if the current route is shorter

if total_distance < best_distance:

best_distance = total_distance

best_route = (0,) + route + (0,) # Include the starting city at the beginning and end of the route

# Print the best route and its distance

print("Best Route:", best_route)

print("Best Distance:", best_distance)

output:
Best Route: (0, 1, 3, 2, 0)
Best Distance: 80

You might also like