1 import numpy as np
2
3 def nearest_neighbor_algorithm(distance_matrix, cities):
4 num_cities = len(cities)
5 unvisited_cities = set(cities[1:]) # Start from the second city
6
7 tour = [cities[0]] # Start from the first city
8 current_city = cities[0]
9
10 while unvisited_cities:
11 nearest_city = min(unvisited_cities, key=lambda city: distance_matrix[cities.index(current_city)][cities.index(city)])
12 tour.append(nearest_city)
13 unvisited_cities.remove(nearest_city)
14 current_city = nearest_city
15
16 # Return to the starting city to complete the tour
17 tour.append(cities[0])
18
19 return tour
20
21 def calculate_total_distance(tour, distance_matrix, cities):
22 total_distance = 0
23 for i in range(len(tour) - 1):
24 current_city = tour[i]
25 next_city = tour[i + 1]
26 total_distance += distance_matrix[cities.index(current_city)][cities.index(next_city)]
27 return total_distance
28
29 # Example distance matrix (replace this with your own)
30 distance_matrix = np.array([
31 [0,42,33,52,29,45],
32 [42,0,26,38,49,30],
33 [33,26,0,34,27,42],
34 [52,38,34,0,35,41],
35 [29,49,27,35,0,31],
36 [45,30,42,41,31,0]
37 ])
38
39 cities = ['A', 'B', 'C', 'D', 'E', 'F']
40
41 # Solve TSP using the nearest neighbor algorithm
42 solution = nearest_neighbor_algorithm(distance_matrix, cities)
43
44 # Calculate the total distance of the tour
45 total_distance = calculate_total_distance(solution, distance_matrix, cities)
46
47 print("Tour:", solution)
48 print("Total Distance:", total_distance)