gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:28:23 25 4
gpt4 key购买 nike

我需要从蓝色圆圈到达红色圆圈。该路径必须包含黑色圆圈(即使它可能不是最佳的)。

Children Trasportation by Bus

我已经包括了节点到节点的距离。通过使用“dijkstra_path”我得到: enter image description here

这是正确的。

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

然后运行算法或其他算法。

谢谢

最佳答案

enter image description here

根据我对您上一条评论的理解,您希望列出经过中间节点的所有可能路径,以便能够选择最短的路径。因此,对于图中的图表,这里是列出从 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

P.S 1- you can add other intermediate nodes if you wish and it should work

2- extracting the shortest path should be easy but I did not include it just to focus on the core of the problem

关于python - 我需要找到源节点和目标节点之间的最短路径(距离)。鉴于必须包含某些节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32780224/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com