Search code examples
c++11dijkstraboost-graph

Make Boost Dijkstra algorithm stop when it reaches a destination node


I'm using boost::graph and its Dijkstra implementation.

When someone is using the Dijkstra algorithm, it may be to know the shortest path between 2 nodes in a graph. But as you need to check all nodes in the graph to find the shortest path, usually (like the boost algorithm) Dijkstra gives you back all the distances between one origin point, and all the other nodes of the graph.

One easy improvement of this algorithm when you only want the path between 2 nodes is to stop it when the algorithm reach the destination node. Then, you are sure that the distance that you have for this final destination node is the shortest one.

How can one tell the boost Dijkstra algorithm to stop when it reaches a specific node ?


Solution

  • You can throw an exception from the visitor: FAQ

    How do I perform an early exit from an algorithm such as BFS?

    Create a visitor that throws an exception when you want to cut off the search, then put your call to breadth_first_search inside of an appropriate try/catch block. This strikes many programmers as a misuse of exceptions, however, much thought was put into the decision to have exceptions has the preferred way to exit early. See boost email discussions for more details.