簡體   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