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')]