问题描述:构建出1m×1m的二维地图,并且其中有100个点,仿真遍历这100个点的最短路径
import matplotlib.pyplot as plt
import numpy as np
from scipy.spatial.distance import pdist, squareform
# 生成随机点
n_points = 100
points = np.random.rand(n_points, 2)
# 绘制地图
fig, ax = plt.subplots()
ax.scatter(points[:, 0], points[:, 1])
ax.set_aspect('equal', 'box')
plt.show()
# 计算距离矩阵
dist_matrix = squareform(pdist(points))
# 近似算法
path = [0]
unvisited = set(range(1, n_points))
while unvisited:
nearest = min(unvisited, key=lambda x: dist_matrix[path[-1], x])
path.append(nearest)
unvisited.remove(nearest)
# 添加回到起点的路径
path.append(0)
# 绘制最短路径
fig, ax = plt.subplots()
ax.scatter(points[:, 0], points[:, 1])
ax.plot(points[path, 0], points[path, 1], '-o')
ax.set_aspect('equal', 'box')
plt.show()
结果: