【问题标题】:find the most efficient path (in term of shortest distance) between a set of 2D points在一组 2D 点之间找到最有效的路径(就最短距离而言)
【发布时间】:2015-12-21 07:06:30
【问题描述】:

我有一组存储在字典中的 2D 点,我需要根据与起点(黄色圆圈)的最短距离,找到对所有点(红色三角形)进行采样的最有效路径。

dict_points = OrderedDict([(0,(0.5129102892466411,1.2791525891782567)),(1,(1.8571436538551014,1.3979619805011203)),(2,(2.796472292985357,1.3021773853592946)),(3,(2.2054745567697513,0.5231652951626251)),(4 , (1.1209493135130593, 0.8220950186969501)), (5, (0.16416153316980153, 0.7241249969879273))])

其中key是点的ID

我的策略很简单。我使用所有可能的点序列(6 个点为 720),并从起点(黄色点)逐点计算欧几里得距离。总距离最短的序列效率最高。

这种方法的问题是对于大量的点变得非常慢

import math
import itertools

base = (2.596, 2.196)

def segments(poly):
    """A sequence of (x,y) numeric coordinates pairs """
    return zip(poly, poly[1:] + [poly[0]])


 def best_path(dict_points, base=None):
    sequence_min_distance = None
    l = dict_points.keys()
    gen = itertools.permutations(l)
    min_dist = float('+inf')
    for index, i in enumerate(gen):
        seq = gen.next()
        seq_list = [dict_points[s] for s in seq]
        if base:
            seq_list.insert(0, base)
        points_paired = segments(seq_list)
        tot_dist = 0
        for points in points_paired:
            dist = math.hypot(points[1][0] - points[0][0], points[1][1] - points[0][1])
            tot_dist += dist
        if tot_dist <= min_dist:
            sequence_min_distance = seq
            min_dist = min(min_dist, tot_dist)
    return sequence_min_distance

best_seq = best_path(dict_points)
(5, 4, 3, 2, 1, 0)

【问题讨论】:

  • 这是traveling salesman problem,没有简单的解决方案。然而,正如那里所描述的,找到相当短但可能不是绝对最短的路径要容易得多。
  • 同意,对于较大的点集,它会变慢。这是一个 NP 难题,蛮力方法将运行 O(n!)

标签: python algorithm performance euclidean-distance


【解决方案1】:

你也可以看看项目tsp-solver https://github.com/dmishin/tsp-solver

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-03
    • 2020-09-18
    • 2018-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多