![](/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.