Python NearestNeighbor 邻近算法求解TSP

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)

无向完全图

Python NearestNeighbor 邻近算法求解TSP_第1张图片

运行结果

运行结果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')]

你可能感兴趣的:(Python,tsp)