蚁群优化算法

#蚁群算法

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))))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值