0
点赞
收藏
分享

微信扫一扫

Julia 利用Plots包绘制TSP求解结果图

Yaphets_巍 2022-04-30 阅读 58

运行结果图:

 

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)
举报

相关推荐

0 条评论