views:

804

answers:

3

I'm using an adjacency_list graph, with undirected and unweighted edges. I need to find a shortest path between vertex u and vertex v. Should I use breadth_first_search() starting from u? When reaching v, how do I obtain the path, and how do I stop the search?

thanks!

A: 

You need to use a minimum spanning tree: search algorithm. It's quite a simple straightforward greedy algorithm.

Jesse Pepper
If I'm not mistaken, a minimum spanning tree will not necessarily contain the shortest path between two specific vertices.
kbo
I think most minimum spanning tree algorithms are not greedy (in the sense of making greedy, suboptimal choices), but they actually find the optimal minimum spanning tree.
@dehmann Not true. There are now two algorithms commonly used, Prim's algorithm and Kruskal's algorithm. Both are greedy algorithms that run in polynomial time. Greedy does not imply a suboptimal choice, it implies taking the best apparent choice without looking at further steps.
Jesse Pepper
@dehmann... http://en.wikipedia.org/wiki/Dijkstra's_algorithm is also greedy (and optimal).
Jesse Pepper
+2  A: 

You should use one of the shortest path algorithms, Dijkstra Shortest Path being the most suitable since you need to find the path between just two vertexes. There is an example for its usage in the boost distribution. There are several options for obtaining output from that function: either by supplying a distance property map or build a predecessor map or writing a custom visitor.

hvintus
The question is concerned with unweighted graphs. To find shortest path in unweighted graph, the easiest method is breadth-first search.Dijkstra's algorithm solves the single-source shortest-paths problem on a weighted, directed graph.
Stephen Hsu
+1  A: 

Yes, do breadth_first_search() starting from u.

FOR every vertex i meet
  IF i==v: BREAK
  record predecessor of i as i.p

To find the shortest path, start from v:

PRINT_PATH(u, v)
  IF v==u
    print u
  ELSEIF v.p==NIL
    print 'no path from u to v exists'
  ELSE PRINT_PATH(u, v.p)
    print v
Stephen Hsu