![](/img/trans.png)
[英]Using R / igraph, is there a way to find a shortest path between nodes taking the count of unique node attributes into account?
[英]I need to find the shortest path (distance) between a source node and a target node. Given that certain nodes MUST be included
計算從藍色圓圈到黑色圓圈的距離。 然后,計算從黑圈到紅圈的距離。 然后,打印所有內容,就好像它是一條路徑一樣。 這具有即使對於“中間”圈子列表也可以工作的優點。
如果他們有特定的訂單(如您在評論中所說),它甚至可以工作!
根據我對您的最后一條評論的理解,您希望列出通過中間節點的所有可能路徑,以便能夠選擇最短的一條。 因此,對於圖中的圖形,這是用於列出從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.