运行结果图:
import Plots
function plot_tour(X, Y, x)
plt = Plots.plot()
for (i, j) in x # 遍历所有的边
Plots.plot!([X[i], X[j]], [Y[i], Y[j]], legend = false)
end
return plt
end
function get_matrix(X,Y)
n = length(X)
d = [sqrt((X[i] - X[j])^2 + (Y[i] - Y[j])^2) for i in 1:n, j in 1:n]
end
function get_edges(result)
# result = [1,2,3,4,5]
number = length(result) # 获取result的元素数量
edges = []
k = 1
while true
if k == number
push!(edges,(result[k],result[1]))
push!(edges,(result[1],result[k]))
break
end
push!(edges,(result[k],result[k+1]))
push!(edges,(result[k+1],result[k]))
k += 1
end
return edges
end
X = [1, 2, 3, 4, 3] # x坐标值
Y = [1, 1, 1, 2, 4] # y坐标值
d = get_matrix(X,Y) # 距离矩阵
result = [1,2,3,4,5] # TSP的结果
edges = get_edges(result) # 关于边与边的连接结果
plot_tour(X, Y, edges)