简体   繁体   中英

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:

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).

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.. :/)

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.

Try using networkx :

import networkx
shortest_path(G, source, target)
  • G is the graph.
  • Source is the starting node.
  • Target is the node at the end of the path.

shortest_path documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM