import itertools
# Function to calculate the total distance for a given path
def calculate_total_distance(path, distance_matrix):
total_distance = 0
for i in range(len(path) - 1):
total_distance += distance_matrix[path[i]][path[i+1]]
total_distance += distance_matrix[path[-1]][path[0]] # Return to the starting
city
return total_distance
# Function to find the shortest path for the TSP problem using brute force
def travelling_salesman_bruteforce(distance_matrix):
# Number of cities
n = len(distance_matrix)
# Generate all permutations of cities (excluding the starting city, city 0)
cities = list(range(1, n))
permutations = itertools.permutations(cities)
# Initialize variables to store the best path and its distance
min_distance = float('inf')
best_path = None
# Try all permutations and calculate the total distance
for perm in permutations:
# Add the starting city (0) at the beginning of the permutation
current_path = [0] + list(perm)
current_distance = calculate_total_distance(current_path, distance_matrix)
# If the current distance is smaller than the minimum distance, update it
if current_distance < min_distance:
min_distance = current_distance
best_path = current_path
return best_path, min_distance
# Function to display the solution
def display_solution(path, distance):
print(f"The best path is: {' -> '.join(map(str, path))}")
print(f"The minimum distance is: {distance}")
# Example usage
if __name__ == "__main__":
distance_matrix = [
[0, 10, 15, 20],
[10, 0, 35, 25],
[15, 35, 0, 30],
[20, 25, 30, 0]
]
best_path, min_distance = travelling_salesman_bruteforce(distance_matrix)
display_solution(best_path, min_distance)