Skip to content

Instantly share code, notes, and snippets.

@faithandbrave
Created April 11, 2012 03:39
Show Gist options
  • Save faithandbrave/2356680 to your computer and use it in GitHub Desktop.
Save faithandbrave/2356680 to your computer and use it in GitHub Desktop.
Suspendable Algorithm using Boost.Context
#include <iostream>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>
#include <boost/assign/list_of.hpp>
#include <functional>
#include "continuation.hpp"
typedef boost::adjacency_list<boost::listS, boost::vecS, boost::directedS,
boost::no_property, boost::property<boost::edge_weight_t, int> > Graph;
typedef std::pair<int, int> Edge;
typedef boost::graph_traits<Graph>::vertex_descriptor Vertex;
enum { S, A, B, C, D, E, F, Z, N };
const std::string Names = "SABCDEFZ";
class path_history_visitor {
continuation& cont;
public:
typedef boost::on_discover_vertex event_filter;
path_history_visitor(continuation& cont) : cont(cont) {}
template<typename Vertex, typename Graph>
void operator()(Vertex v, const Graph&)
{
std::cout << Names[v] << ' ';
cont.suspend();
}
};
Graph make_graph()
{
const std::vector<Edge> edges = boost::assign::list_of<Edge>
(S, A)
(A, B)
(B, C)
(B, D)
(C, E)
(C, F)
(D, F)
(E, D)
(F, E)
(E, Z)
(F, Z)
;
const std::vector<int> weights = boost::assign::list_of
(3)
(1)
(2)
(3)
(7)
(12)
(2)
(11)
(3)
(2)
(2)
;
return Graph(edges.begin(), edges.end(), weights.begin(), N);
}
int main()
{
const Graph g = make_graph();
const Vertex from = S;
continuation cont = [&](continuation& cont) {
path_history_visitor vis(cont);
boost::dijkstra_shortest_paths(g, from,
boost::visitor(boost::make_dijkstra_visitor(vis)));
};
while (!cont.is_complete()) {
cont.resume();
}
}
/*
output:
S A B C D E F Z
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment