#蚁群算法
import random
distance_matrix = [
[0, 29, 20, 21],
[29, 0, 15, 18],
[20, 15, 0, 28],
[21, 18, 28, 0]
]
# 参数设置
num_ants = 4
num_iterations = 100
evaporation_rate = 0.5
pheromone_deposit = 1.0
# 初始化信息素浓度矩阵
pheromone_matrix = [[1.0] * len(distance_matrix) for _ in range(len(distance_matrix))]
# 主循环
for iteration in range(num_iterations):
ant_tours = []
# 每只蚂蚁构建路径
for ant in range(num_ants):
current_city = random.randint(0, len(distance_matrix) - 1)
tour = [current_city]
while len(tour) < len(distance_matrix):
# 计算每个未访问城市的选择概率
unvisited_cities = [city for city in range(len(distance_matrix)) if city not in tour]
probabilities = [((pheromone_matrix[current_city][next_city] ** 2) / distance_matrix[current_city][next_city])
for next_city in unvisited_cities]
total_probability = sum(probabilities)
# 使用轮盘赌选择下一个城市
random_value = random.uniform(0, total_probability)
next_city = None
cumulative_probability = 0
for i, probability in enumerate(probabilities):
cumulative_probability += probability
if cumulative_probability >= random_value:
next_city = unvisited_cities[i]
break
tour.append(next_city)
current_city = next_city
ant_tours.append(tour)
# 更新信息素浓度
for i in range(len(distance_matrix)):
for j in range(len(distance_matrix)):
if i != j:
pheromone_matrix[i][j] *= (1 - evaporation_rate)
for tour in ant_tours:
tour_length = sum(distance_matrix[tour[i - 1]][tour[i]] for i in range(1, len(tour)))
for i in range(len(tour) - 1):
pheromone_matrix[tour[i]][tour[i + 1]] += pheromone_deposit / tour_length
# 找到最佳路径
best_tour = min(ant_tours, key=lambda tour: sum(distance_matrix[tour[i - 1]][tour[i]] for i in range(1, len(tour)))
)
print("Best Tour:", best_tour)
print("Tour Length:", sum(distance_matrix[best_tour[i - 1]][best_tour[i]] for i in range(1, len(best_tour))))