输入:无向连通图
输出:TSP路径
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')]