以下是使用贪心策略求解TSP问题的Python代码:
import numpy as np
def tsp_greedy(distances):
n_cities = distances.shape[0]
current_city = 0
unvisited_cities = set(range(1, n_cities))
path = [current_city]
total_distance = 0
for i in range(n_cities - 1):
nearest_city = min(unvisited_cities, key=lambda city: distances[current_city][city])
unvisited_cities.remove(nearest_city)
path.append(nearest_city)
total_distance += distances[current_city][nearest_city]
current_city = nearest_city
total_distance += distances[current_city][0]
path.append(0)
return path, total_distance
# Example usage
distances = np.array([[0, 2, 4, 8], [2, 0, 2, 5], [4, 2, 0, 7], [8, 5, 7, 0]])
path, distance = tsp_greedy(distances)
print("Path:", path)
print("Distance:", distance)
请注意,这只是一种简单的贪心策略,并不能保证得到最优解。