簡體   English   中英

我需要找到源節點和目標節點之間的最短路徑(距離)。 鑒於必須包含某些節點

[英]I need to find the shortest path (distance) between a source node and a target node. Given that certain nodes MUST be included

我需要從藍色圓圈轉到紅色圓圈。 該路徑必須包括黑色圓圈( 即使可能不是最佳)。

兒童乘巴士運輸

我已經包括了節點之間的距離。 通過使用'dijkstra_path'我得到: 在此處輸入圖片說明

哪個是對的。

但是...我該怎么做才能確保包括“ kountoumas”甚至其他節點的列表。

然后運行該算法或其他算法。

謝謝

計算從藍色圓圈到黑色圓圈的距離。 然后,計算從黑圈到紅圈的距離。 然后,打印所有內容,就好像它是一條路徑一樣。 這具有即使對於“中間”圈子列表也可以工作的優點。

如果他們有特定的訂單(如您在評論中所說),它甚至可以工作!

在此處輸入圖片說明

根據我對您的最后一條評論的理解,您希望列出通過中間節點的所有可能路徑,以便能夠選擇最短的一條。 因此,對於圖中的圖形,這是用於列出從1到2的所有可能路徑分別作為第一個節點和最后一個節點以及中間節點3和4的代碼。我添加了一些注釋,試圖使其盡可能清楚。

start = 1 # starting node for the path (fixed)
end = 2 # last node in the path (fixed)
intermediate = [4,3] # Intermediate nodes that the path must include
#permutations of intermediate nodes to find shortest path
p =  list(it.permutations(intermediate))
print "Possible orders of intermediate nodes", p, '\n'
hops_tmp = 0
path_tmp = [] # stores path for each permutation
sub_path_tmp = [] # stores sub path from one node to another
for j in xrange(len(p)): # loop for all permutations possibilities
    # path from starting node to the first intermediate node
    sub_path_tmp = nx.dijkstra_path(G,start,p[j][0]) 
    for k in xrange(len(sub_path_tmp)): # update path with sub_path
        path_tmp.append(sub_path_tmp[k])
    #loop to find path from intermediate to another upto the last node
    for i in xrange(len(intermediate)):
        # if last intermediate node calculate path to last node
        if i == len(intermediate) - 1:
            sub_path_tmp =  nx.dijkstra_path(G,p[j][i],end)
        else: # otherwise calculate path to the next intermediate node
            sub_path_tmp =  nx.dijkstra_path(G,p[j][i],p[j][i+1]) 
        for k in xrange(len(sub_path_tmp)-1): # update path with sub_path
            path_tmp.append(sub_path_tmp[k+1])
    hops_tmp = len(path_tmp) -1
    print path_tmp
    print hops_tmp , '\n'
    # Reset path and hops for the next permutation
    hops_tmp = 0
    path_tmp = []

結果如下:

 Possible orders of intermediate nodes [(4, 3), (3, 4)] 

 [1, 8, 4, 8, 1, 3, 7, 5, 9, 2]

 9

 [1, 3, 1, 8, 4, 5, 9, 2]

 7 

PS 1-如果需要,您可以添加其他中間節點,它應該可以工作

2-提取最短路徑應該很容易,但我並沒有將其包括在內只是為了關注問題的核心

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM