繁体   English   中英

最短路径tsp算法

[英]shortest path tsp algorithm

现在下面是字典,我正在尝试找到最短的路径。我们必须根据最短的时间前往所有5所房屋。 每个键都是一所房子,每个值列表都是以秒为单位的时间。 例如,第一宫的时间为0,因为很明显,现在从第一宫到第二宫的时间为74秒……等等。 每个索引都是到下一所房子的时间表示。

现在第二行,以2作为键。 从第二宫到第一宫的时间是74秒,现在从第二宫到第三宫的时间是4069秒,如下所示。

我正试图为此找到最好的算法,我很困惑我应该使用什么? 组合? 排列?

目的是找到从房屋到房屋的最短路径,并在下面进行重新设置,并以找到的最短路径求出所有时间的总和

list = 0, 74 , 2213, 816, 1172 ,

最短的路径。

1 -> 2 -> 5 -> 4 -> 3 -> 1 

我们必须回到第一宫,这就是为什么再次显示1

1至5,代表房屋清单

  1. 遍历每个键,值找到最小值和最小值的索引。 将时间添加到time_list

  2. 使用上一个找到的索引访问下一个房屋(钥匙)

  3. 将min的索引匹配到下一个房屋,在房屋中忽略零,并且以前的房屋时间已经遇到过的时间

您可以尝试通过跟踪当前房屋和迄今为止访问的所有房屋来减少要检查的路径数量。 假设您有路径[1, 2, 3, 4][1, 3, 2, 4]您可以检查哪个更短,然后继续。 这是您提供的数据的示例,它以2D数组而不是dict存储距离,但是原理是相同的:

dist = [
    [0, 74, 4109, 3047, 2266], 
    [74, 0, 4069, 2999, 2213],
    [4109, 4069, 0, 1172, 1972], 
    [3047, 2999, 1172, 0, 816], 
    [2266, 2213, 1972, 816, 0]
]

# Helper function to calculate path length
def path_len(path):
    return sum(dist[i][j] for i, j in zip(path, path[1:]))

# Set of all nodes to visit
to_visit = set(xrange(len(dist)))

# Current state {(node, visited_nodes): shortest_path}
state = {(i, frozenset([0, i])): [0, i] for i in xrange(1, len(dist[0]))}

for _ in xrange(len(dist) - 2):
    next_state = {}
    for position, path in state.iteritems():
        current_node, visited = position

        # Check all nodes that haven't been visited so far
        for node in to_visit - visited:
            new_path = path + [node]
            new_pos = (node, frozenset(new_path))

            # Update if (current node, visited) is not in next state or we found shorter path
            if new_pos not in next_state or path_len(new_path) < path_len(next_state[new_pos]):
                next_state[new_pos] = new_path

    state = next_state

# Find the shortest path from possible candidates
shortest = min((path + [0] for path in state.itervalues()), key=path_len)
print 'path: {0}, length: {1}'.format(shortest, path_len(shortest))

它将输出最短路径之一和总距离:

path: [0, 2, 3, 4, 1, 0], length: 8384

请注意,对于您提供的数据,有两种可能的解决方案,它们的长度相等: [0, 2, 3, 4, 1, 0][0, 1, 4, 3, 2, 0]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM