Python NearestNeighbor 邻近算法求解TSP

3 篇文章 0 订阅

NearestNeighbor 邻近算法

输入:无向连通图
输出:TSP路径

运行环境

  • Python3.6
  • Numpy 1.17.3

代码函数说明

  • NearestNeighbor(G, label)
  • 任选一个城市开始,到达离它最近的城市,然后从该城市出发,选择离它最近的未访问过的城市,重复该过程,直到所有城市都被访问过,再回到开始城市。

代码实现

import numpy as np

def NearestNeighbor(G, label):
    length = len(G)
    vertices = []
    H = []
    s = np.random.randint(len(G))
    v = s
    while v not in vertices:
        w = 10000003
        index = -1
        for i in range(length):
            if i not in vertices and i != v and G[v][i] < w:
                w = G[v][i]
                index = i
        if w == 10000003 or index == -1:
            break
        H.append((label[v], label[index]))
        vertices.append(v)
        v = index
    return H

G = [
    [0,20,15,35],
    [20,0,10,25],
    [15,10,0,12],
    [35,25,12,0]
]
label = ['a', 'b', 'c', 'd']
result = NearestNeighbor(G, label)
print(result)

无向完全图

在这里插入图片描述

运行结果

运行结果1[('a', 'c'), ('c', 'b'), ('b', 'd')]
运行结果2[('b', 'c'), ('c', 'd'), ('d', 'a')]
运行结果3[('c', 'b'), ('b', 'a'), ('a', 'd')]
运行结果4
[('d', 'c'), ('c', 'b'), ('b', 'a')]
  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
蚁群算法(Ant Colony Optimization,简称ACO)是一种基于模拟蚂蚁觅食行为的优化算法,常用于求解旅行商问题(Traveling Salesman Problem,简称TSP)。下面是使用Python实现蚁群算法求解TSP的基本步骤: 1. 定义TSP问题的输入,包括城市数量、城市间距离矩阵等。 2. 初始化蚂蚁群和相关参数,包括蚂蚁数量、信息素浓度、信息素挥发率、启发式因子等。 3. 对每只蚂蚁进行路径选择和更新。 - 蚂蚁按照一定的规则选择下一个要访问的城市,可以利用信息素浓度和启发式因子来决定选择概率。 - 每只蚂蚁完成一次路径选择后,更新路径长度和信息素浓度。 4. 更新全局最优路径。 - 在所有蚂蚁完成路径选择后,根据各个路径长度更新全局最优路径。 5. 更新信息素浓度。 - 通过信息素挥发和新的信息素分泌来更新每条路径上的信息素浓度。 6. 重复步骤3-5,直到满足停止条件(如迭代次数达到限制或找到较优解)。 下面是一个简单的Python代码示例: ```python import numpy as np def ant_colony_optimization(cities, num_ants, num_iterations, evaporation_rate, alpha, beta): num_cities = len(cities) pheromone = np.ones((num_cities, num_cities)) # 初始化信息素浓度矩阵 best_path = None best_length = float('inf') for _ in range(num_iterations): paths = [] lengths = [] for _ in range(num_ants): path = [] length = 0 current_city = np.random.randint(num_cities) unvisited_cities = set(range(num_cities)) unvisited_cities.remove(current_city) while unvisited_cities: next_city = select_next_city(current_city, unvisited_cities, pheromone, alpha, beta) path.append(next_city) length += cities[current_city][next_city] current_city = next_city unvisited_cities.remove(current_city) path.append(path[0]) # 回到起始城市 length += cities[current_city][path[0]] paths.append(path) lengths.append(length) if length < best_length: best_path = path best_length = length update_pheromone(pheromone, paths, lengths, evaporation_rate) return best_path, best_length def select_next_city(current_city, unvisited_cities, pheromone, alpha, beta): probabilities = [] total_sum = 0 for city in unvisited_cities: pheromone_sum = np.sum(pheromone[current_city, list(unvisited_cities)]) heuristic_value = 1 / cities[current_city][city] probability = (pheromone[current_city, city] ** alpha) * (heuristic_value ** beta) probabilities.append(probability) total_sum += probability probabilities = [p / total_sum for p in probabilities] next_city = np.random.choice(list(unvisited_cities), p=probabilities) return next_city def update_pheromone(pheromone, paths, lengths, evaporation_rate): pheromone *= (1 - evaporation_rate) # 信息素挥发 for i in range(len(paths)): path = paths[i] length = lengths[i] for j in range(len(path) - 1): city1 = path[j] city2 = path[j + 1] pheromone[city1][city2] += 1 / length ``` 在代码中,cities是城市间距离矩阵,num_ants是蚂蚁数量,num_iterations是迭代次数,evaporation_rate是信息素挥发率,alpha和beta是启发式因子。通过调用`ant_colony_optimization`函数,可以得到最优路径(best_path)和路径长度(best_length)。 希望对你有所帮助!如有其他问题,请继续提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值