我需要找到源节点和目标节点之间的最短路径(距离)。鉴于必须包含某些节点

时间:2015-09-25 10:29:52

标签: python networkx

我需要从蓝色圈子转到红色圈子。路径必须包含黑色圈,(即使也可能不是最佳选择)。

Children Trasportation by Bus

我已经包含了从节点到节点的距离。并通过使用'dijkstra_path'我得到: enter image description here

这是正确的。

但是......我该怎样做才能确保包含'kountoumas',甚至包含其他节点列表。

然后运行算法或另一个算法。

谢谢

2 个答案:

答案 0 :(得分:1)

计算从蓝色圆圈到黑色圆圈的距离。然后,计算从黑色圆圈到红色圆圈的距离。然后,打印所有内容,就好像它是一条路径一样。这样做的好处是甚至可以用于"中介"圆。

如果他们有特定的订单,就会有效(正如你在评论中所说的那样)!

答案 1 :(得分:1)

enter image description here

根据我对您上次评论的理解,您希望列出通过中间节点的所有可能路径,以便能够选择最短的路径。因此,对于图中的图形,这里是用于列出从1到2的所有可能路径的代码,分别作为第一个和最后一个节点,具有中间节点3和4.我添加了一些注释以尽量使其尽可能清楚。

$ yes | zsh -c 'read -sk 1 "RESPONSE?[Y/n] " ; echo $RESPONSE'
[Y/n]

结果如下:

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 = []
  

P.S 1-如果您愿意,可以添加其他中间节点,它应该可以正常工作

     

2-提取最短路径应该很容易,但我没有把它包括在内,只关注问题的核心