2
votes

I have a list of interconnected edges (E), how can I find the shortest path connecting from one vertex to another?

I am thinking about using lowest common ancestors, but the edges don't have a clearly defined root, so I don't think the solution works.

Shortest path is defined by the minimum number of vertexes traversed.

Note: There could be a multi-path connecting two vertices, so obviously breadth first search won't work

5
Note that lowest common ancestors requires a tree, which implies that there's only one path between any two nodes. Finding the shortest path is trivial in that case. - outis
I don't see how having multiple possible paths defeats using BFS. BFS finds the shortest path from a single node in a graph, provided all edges are unweighted/have same weight. The graph does not have to be a tree for BFS to work. - MAK

5 Answers

9
votes

Dijkstra's algorithm will do this for you.

8
votes

I'm not sure if you need a path between every pair of nodes or between two particular nodes. Since someone has already given an answer addressing the former, I will address the latter.

If you don't have any prior knowledge about the graph (if you do, you can use a heuristic-based search such as A*) then you should use a breadth-first search.

2
votes

The Floyd-Warshall algorithm would be a possible solution to your problem, but there are also other solutions to solve the all-pairs shortest path problem.

1
votes
Shortest path is defined by the minimum number of vertexes treversed

it is same as minimum number of edges plus one.

you can use standard breadth first search and it will work fine. If you have more than one path connecting two vertices just save one of them it will not affect anything, because weight of every edge is 1.

0
votes

Additional 2 cents. Take a look at networkx. There are interesting algos already implemented for what you need, and you can choose the best suited.