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()
相关推荐
Xiaok10188 分钟前
解决 Hugging Face SentenceTransformer 下载失败的完整指南:ProxyError、SSLError与手动下载方案
开发语言·神经网络·php
CryptoPP9 分钟前
springboot 对接马来西亚数据源API等多个国家的数据源
spring boot·后端·python·金融·区块链
绿草在线10 分钟前
Mock.js虚拟接口
开发语言·javascript·ecmascript
xcLeigh17 分钟前
OpenCV从零开始:30天掌握图像处理基础
图像处理·人工智能·python·opencv
大乔乔布斯17 分钟前
AttributeError: module ‘smtplib‘ has no attribute ‘SMTP_SSL‘ 解决方法
python·bash·ssl
go_bai20 分钟前
Linux环境基础开发工具——(2)vim
linux·开发语言·经验分享·笔记·vim·学习方法
小郝 小郝22 分钟前
【C语言】strstr查找字符串函数
c语言·开发语言
yinhezhanshen27 分钟前
理解rust里面的copy和clone
开发语言·后端·rust
明灯L30 分钟前
《函数基础与内存机制深度剖析:从 return 语句到各类经典编程题详解》
经验分享·python·算法·链表·经典例题
databook31 分钟前
不平衡样本数据的救星:数据再分配策略
python·机器学习·scikit-learn