[英]How can I find the distance between 2 nodes given a list of edges (directed) of a graph?
Suppose I have the edge set as a list containing the edges as follows: 假设我将边设置为包含边的列表,如下所示:
E=[(1, 6), (1, 7), (2, 3), (2, 6), (3, 2), (3, 8), (4, 5), (4, 7), (5, 4), (5, 9), (6, 1), (6, 7), (6, 2), (7, 1), (7, 6), (7, 4), (8, 9), (8, 3), (9, 8), (9, 5)]
I will like to find the shortest path between nodes 8 and 4 (and also considering the case where there are 2 shortest paths of equal distance), given the distance matrix: 给定距离矩阵,我想找到节点8和4之间的最短路径(并且还要考虑存在两个等距离的最短路径的情况):
C=[2.5, 5.59, 1.0, 2.0, 1.0, 2.0, 1.0, 2.0, 1.0, 2.0, 2.5, 5.0, 2.0, 5.59, 5.0, 2.0, 5.0, 2.0, 5.0, 2.0]
where each element in C
(say in the i-th position) corresponds to the distance between the 2 nodes of the corresponding edge in E
(at the i-th position). 其中
C
中的每个元素(例如在第i个位置)对应于E
相应边缘(在第i个位置)的两个节点之间的距离。
I have chanced upon somewhat similar posts which encourages the use of Dijkstra's algorithm, but I have not found one that does it in Python 3.5x (maybe there is but I just cannot find it.. :/) 我偶然发现了一些类似的文章,鼓励使用Dijkstra的算法,但是我还没有找到在Python 3.5x中能做到这一点的文章(也许有,但是我找不到它..:/)
Thus, to add on to my question above, besides finding the minimum distance between nodes 8 and 4, I will also like to generalize it to finding the minimum distance between any 2 nodes given the edge set and distance matrix. 因此,除了上面提到的问题外,除了找到节点8和4之间的最小距离外,我还想将其推广到给定边集和距离矩阵的情况下,找到任意两个节点之间的最小距离。
Try using networkx
: 尝试使用
networkx
:
import networkx
shortest_path(G, source, target)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.