tsp可视化python

随机生成点的坐标并依据点集生成距离矩阵,通过点的坐标实现可视化

c代码看我的这篇文章tsp动态规划递归解法c++

python 复制代码
from typing import List, Tuple
import matplotlib.pyplot as plt
from random import randint

N: int = 4
MAX: int = 0x7f7f7f7f

distances: List[List[int]] = [[0 for _ in range(N)] for _ in range(N)]
path: List[List[int]] = [[0 for _ in range(1 << (N - 1))] for _ in range(N)]
dp: List[List[int]] = [[0 for _ in range(1 << (N - 1))] for _ in range(N)]
points: List[Tuple[int, int ]]

def creatDistances():
    global distances, dp
    # for i in range(N):
    #     for j in range(N):
    #         if i == j:
    #             distances[i][j] = MAX
    #         else:
    #             temp = randint(1, 10)
    #             while temp == 0:
    #                 temp = randint(1, 10)
    #             distances[i][j] = temp
    # x=[[MAX, 3, 6, 7],
    #    [5, MAX, 2, 3],
    #    [6, 4, MAX, 2],
    #    [3, 7, 5, MAX]]
    # for i in range(N):
    #     for j in range(N):
    #         distances[i][j] = x[i][j]
    creatpoints()
    for i in range(N):
        dp[i][0] = distances[i][0]


def printDistances():
    global distances
    print("代价矩阵为:")
    for i in range(N):
        for j in range(N):
            if distances[i][j] == MAX:
                s = "INF"
                print(f"{s:<17}", end=" ")
            else:
                print(f"{distances[i][j]:<17}", end=" ")
        print()
    for i, point in enumerate(points):
        plt.text(*point, f'{i }', fontsize=12, ha='center', va='bottom')
    plt.scatter(*zip(*points))

def removeCity(j: int, k: int) -> int:
    return j - (1 << (k - 1))


def printPath(i: int, j: int) -> None:
    if j != 0:
        print(f"{i} -> ", end="")
        next_city = path[i][j]
        plt.plot((points[i][0],points[next_city][0]), (points[i][1],points[next_city][1]))
        printPath(next_city, removeCity(j, next_city))
    else:
        print(f"{i} -> {0}")
        plt.plot((points[i][0],0), (points[i][1],0))


def creatpoints() ->None:
    ldasc: int = 1
    hdasc: int = 10
    dapr: int = N - 1
    global points
    points = [(0,0)]+[(randint(ldasc, hdasc), randint(ldasc, hdasc)) for i in range(dapr)]
    for i in range(N):
        for j in range(i, N):
            if i == j:
                distances[i][j] = MAX
            else:
                distances[i][j] = distances[j][i] = ((points[i][0]-points[j][0])**2+(points[i][1]-points[j][1])**2)**.5
def drewpoints() ->None:
    global points



def TSP(v: int, s: int) -> int:
    global distances, dp, path
    if dp[v][s] != 0:
        return dp[v][s]
    min = MAX
    for k in range(1, N):
        if ((s >> (k - 1)) & 1) == 1:
            t = TSP(k, removeCity(s, k))
            if (t + distances[v][k]) < min:
                min = t + distances[v][k]
                path[v][s] = k
    dp[v][s] = min
    return min


if __name__ == "__main__":
    creatDistances()
    printDistances()
    print(f"最短距离为:{TSP(0, (1 << (N - 1)) - 1)}")
    print("最短路径为:")
    printPath(0, (1 << (N - 1)) - 1)
    print(points)
    plt.show()
相关推荐
生信摆渡4 分钟前
R语言-快速对多个变量取交集
开发语言·数据库·r语言
¥ 多多¥17 分钟前
c++中mystring运算符重载
开发语言·c++·算法
LKID体18 分钟前
Python操作neo4j库py2neo使用(一)
python·oracle·neo4j
Mr.Pascal23 分钟前
刚学php序列化/反序列化遇到的坑(攻防世界:Web_php_unserialize)
开发语言·安全·web安全·php
小尤笔记35 分钟前
利用Python编写简单登录系统
开发语言·python·数据分析·python基础
秦老师Q38 分钟前
Java基础第九章-Java集合框架(超详细)!!!
java·开发语言
计算机毕设源码qq-383653104139 分钟前
(附项目源码)Java开发语言,215 springboot 大学生爱心互助代购网站,计算机毕设程序开发+文案(LW+PPT)
java·开发语言·spring boot·mysql·课程设计
FreedomLeo140 分钟前
Python数据分析NumPy和pandas(四十、Python 中的建模库statsmodels 和 scikit-learn)
python·机器学习·数据分析·scikit-learn·statsmodels·numpy和pandas
无尽的大道1 小时前
深入理解 Java 阻塞队列:使用场景、原理与性能优化
java·开发语言·性能优化
建群新人小猿1 小时前
会员等级经验问题
android·开发语言·前端·javascript·php