Find the shortest Path between two nodes (vertices)

15,461

Solution 1

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.

Solution 2

Dijkstra's algorithm will do this for you.

Solution 3

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.

Solution 4

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.

Share:
15,461
Graviton
Author by

Graviton

A software developer.

Updated on June 05, 2022

Comments

  • Graviton
    Graviton almost 2 years

    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

  • John Kugelman
    John Kugelman over 14 years
    Only needed if edges are weighted.
  • Graviton
    Graviton over 14 years
    bfs will tell me a path between two nodes; but it can't tell me which path is the shortest one.
  • monksy
    monksy over 14 years
    I forgot about that... I assumed that his map of edges were weights.
  • seanmonstar
    seanmonstar over 14 years
    if not weighted, simply assume all edges weigh 1. still a good solution.
  • Artelius
    Artelius over 14 years
    Oops, BFS gives you the shortest path for unweighted edges.