Make Boost Dijkstra algorithm stop when it reaches a destination node - c++11

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 ?

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.

Thanks to Sehe and his insights, I followed the road of the Dijkstra Visitors to solve my problem. Here is the solution :
I created a visitor class that came from the Dijkstra's visitor types :
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/breadth_first_search.hpp>
// Graph Definitions
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS> Graph;
typedef boost::graph_traits<Graph>::vertex_descriptor Vertex;
typedef boost::graph_traits<Graph>::edge_descriptor Edge;
// Visitor that throw an exception when finishing the destination vertex
class my_visitor : boost::default_bfs_visitor{
protected:
Vertex destination_vertex_m;
public:
my_visitor(Vertex destination_vertex_l)
: destination_vertex_m(destination_vertex_l) {};
void initialize_vertex(const Vertex &s, const Graph &g) const {}
void discover_vertex(const Vertex &s, const Graph &g) const {}
void examine_vertex(const Vertex &s, const Graph &g) const {}
void examine_edge(const Edge &e, const Graph &g) const {}
void edge_relaxed(const Edge &e, const Graph &g) const {}
void edge_not_relaxed(const Edge &e, const Graph &g) const {}
void finish_vertex(const Vertex &s, const Graph &g) const {
if (destination_vertex_m == s)
throw(2);
}
};
And then I launched Boost Dijkstra with a try-catch block to get the exception
// To store predecessor
std::vector<Vertex> predecessor_map_p (boost::num_vertices(graph_m));
// To store distances
std::vector<double> distance_map_p (boost::num_vertices(graph_m));
// Vertex that will have set to the origin and the destination :
Vertex vertex_origin_num_p,vertex_destination_num_p;
// Visitor to throw an exception when the end is reached
my_visitor vis(vertex_destination_num_p);
try {
boost::dijkstra_shortest_paths(
graph_m,
vertex_origin_num_p,
predecessor_map(boost::make_iterator_property_map(predecessor_map_p->data(), vid_l)).
distance_map(boost::make_iterator_property_map(distance_map_p->data(), vid_l)).
visitor(vis)
);
}
catch (int exception) {
std::cout << "The Dijsktra algorithm stopped" << std::endl;
}

Related

Populate a tree from vectors with BGL

I have two vectors of objects that I need to make a tree structure from them. Let's assume we have vector <obj> parents and vector <obj> leaves. Therefore, each element of vector <obj> parents has several leaves that sits at the end of the tree. What I am doing is defining Vertex properties and Edges properties as below, and then define a bidirectional graph:
struct VertexData
{
std::string obj_name; // concatenation of labels
std::string obj_class_num;
int num;
vector <int> segments_list;
bool is_leaf=false;
};
struct EdgeData
{
std::string edge_name;
double confidence;
};
typedef boost::adjacency_list<boost::vecS, boost::vecS,
boost::bidirectionalS,
VertexData,
boost::property<boost::edge_weight_t, double, EdgeData> > Graph;
Graph graph;
First approach: looping through the vector <obj> leaves, for each member, I find the parent and make an edge. Then assign properties to the edge and vertices. But then for next leaf, I should check if already it has a parent in the tree or I should add a new vertex for its parent.
Second approach: another thing that I tried, was looping through the vector <obj> parents, and for each element try to make its leaves. But I am not sure what is the correct way to do this.
Here is a link:
adding custom vertices to a boost graph that I try to do the same but with iterations.
Code added for 1st approach:
vector <class1> parents; // this has some objects of type class1
vector <class2> leaves; // this has some objects of type class2
/// declare the graph
typedef boost::adjacency_list<boost::vecS, boost::vecS,
boost::bidirectionalS,
VertexData,
boost::property<boost::edge_weight_t, double, EdgeData> > Graph;
/// instantiate the graph
Graph graph;
typedef boost::graph_traits<Graph>::vertex_descriptor vertex_t;
typedef boost::graph_traits<Graph>::edge_descriptor edge_t;
vector<vertex_t> obj_vertices;
vector<string> parents_labels_v;
bool parent_exist=false;
/// loop through leaves and make edges with associated parent
for (auto leaf: leaves) {
int leaf_nr = leaf.Number;
vertex_t v = boost::add_vertex(graph); // this is the leaf vertex
graph[v].num = leaf_nr; // leaf number
graph[v].is_leaf = true;
/// access the parent label by leaf number
string label1 = parents[leaf_nr].label;
/// check if the parent already exist, using its label
if(std::find(parents_labels_v.begin(), parents_labels_v.end(), label1)
!= parents_labels_v.end()){
parent_exist = true;
}else{
parents_labels_v.push_back(label1);
}
if(parent_exist) {
// find already_exist parent vertex to make the edge
vertex_t u = ??? here i have problem
// Create an edge connecting those two vertices
edge_t e; bool b;
boost::tie(e,b) = boost::add_edge(u,v,graph);
} else{
// if parent-vertex there is not, add it to the graph
vertex_t u = boost::add_vertex(graph); // this is the parent vertex
graph[u].obj_name = label1;
graph[u].segments_list.push_back(leaf_nr);
obj_vertices.push_back(u);
// Create an edge connecting those two vertices
edge_t e; bool b;
boost::tie(e,b) = boost::add_edge(u,v,graph);
}
}

Number of connected components after deleting k vertices

I am trying to solve the following graph problem:
We are given a general unweighted and undirected graph and k (k < |V| ) vertices that are
already known beforehand. The vertices are deleted sequentially. After
each deletion, how many connected components are there?
I thought of using tarjan's algorithm at each step to check if the current vertex to be deleted is a cut vertex so that when the deletion is performed, we can simply add the number of neighbours to the number of connected components. The complexity of this algorithm is O(V(V+E)).
I was told that there is a O(V+E) algorithm to perform this task. But I cannot figure it out. Research on Google also does not reveal much. Could anyone please advise me?
We can use the fact that the vertices are known beforehand.
Let's solve a "reverse" problem: given a graph and a list vertices that are ADDED to it sequentially, compute the number of connected components in the graph after each addition structure.
The solution is pretty straightforward: we can maintain a disjoint set union structure and add all edges incident to the vertex to the graph (it's easy to keep the number of components in this structure: initially, it is equal to the number of vertices and is decreased by one when a union actually happens).
The original problem is reduced to the "reverse" one in the following way:
Let's add all edges that are not incident to any of the deleted vertices to the disjoint set union.
Now we can reverse the list of deleted vertices and add them one by one as described above.
After that, we need to reverse the resulting list that contains the number of components.
Note: this solution is not actually O(V + E), its O(V + E * alpha(V)), where alpha(x) is the inverse Ackermann's function. It is very close to linear for all practical purposes.
here is my implementation of algorithm in c++ using disjoint set:
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
typedef pair<int, int> pii;
const int M=2e5+137;
class DisjointSet {
public:
int connected_comp;
int parent[100000];
void makeSet(int n){
for (int i=1;i<n+1; ++i)
parent[i] = i;
connected_comp = n;
}
int Find(int l) {
if (parent[l] == l)
return l;
return Find(parent[l]);
}
void Union(int m, int n) {
int x = Find(m);
int y = Find(n);
if(x==y) return;
if(x<y){
parent[y] = x;
connected_comp--;
}
else{
parent[x] = y;
connected_comp--;
}
}
};
set<pii> not_delete;
vector<pii> to_add;
int main(){
int node, edge;
cout<<"enter number of nodes and edges"<<"\n";
cin>>node>>edge;
DisjointSet dis;
dis.makeSet(node);
cout<<"enter two nodes to add edges"<<"\n";
for(int i=0;i<edge;i++){
int u,v;
cin>>u>>v;
if(u>v){
not_delete.insert({u,v});
}
else{
not_delete.insert({v,u});
}
}
int deletions;
cout<<"enter number of deletions"<<"\n";
cin>>deletions;
cout<<"enter two node to delete edge between them"<<"\n";
for(int i=0;i<deletions;i++){
int u,v;
cin>>u>>v;
if(u>v){
not_delete.erase({u,v});// edges that never delete from graph
to_add.pb({u,v}); // edges that gonna delete from graph
}
else{
not_delete.erase({v,u});
to_add.pb({v,u});
}
}
vector<int> res;
// first adding edges that never delete from graph
for(pii x: not_delete){
dis.Union(x.first, x.second);
}
res.pb(dis.connected_comp);
// then adding edges that will be deleted from graph backwards
reverse(to_add.begin(), to_add.end());
for(pii x: to_add){
dis.Union(x.first, x.second);
res.pb(dis.connected_comp);
}
cout<<"connected components after each deletion:"<<"\n";
for (auto it = ++res.rbegin(); it != res.rend(); ++it)
cout << *it << "\n";
return 0;
}

Detected Cycle in directed graph if the vertex is found in recursive stack-why?

I have read an article from here about how to detect cycle in a directed graph. The basic concept of this algorithm is if a node is found in recursive stack then there is a cycle, but i don't understand why. what is the logic here?
#include<iostream>
#include <list>
#include <limits.h>
using namespace std;
class Graph
{
int V; // No. of vertices
list<int> *adj; // Pointer to an array containing adjacency lists
bool isCyclicUtil(int v, bool visited[], bool *rs);
public:
Graph(int V); // Constructor
void addEdge(int v, int w); // to add an edge to graph
bool isCyclic(); // returns true if there is a cycle in this graph
};
Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V];
}
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w); // Add w to v’s list.
}
bool Graph::isCyclicUtil(int v, bool visited[], bool *recStack)
{
if(visited[v] == false)
{
// Mark the current node as visited and part of recursion stack
visited[v] = true;
recStack[v] = true;
// Recur for all the vertices adjacent to this vertex
list<int>::iterator i;
for(i = adj[v].begin(); i != adj[v].end(); ++i)
{
if ( !visited[*i] && isCyclicUtil(*i, visited, recStack) )
return true;
else if (recStack[*i])
return true;
}
}
recStack[v] = false; // remove the vertex from recursion stack
return false;
}
bool Graph::isCyclic()
{
// Mark all the vertices as not visited and not part of recursion
// stack
bool *visited = new bool[V];
bool *recStack = new bool[V];
for(int i = 0; i < V; i++)
{
visited[i] = false;
recStack[i] = false;
}
for(int i = 0; i < V; i++)
if (isCyclicUtil(i, visited, recStack))
return true;
return false;
}
int main()
{
// Create a graph given in the above diagram
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
if(g.isCyclic())
cout << "Graph contains cycle";
else
cout << "Graph doesn't contain cycle";
return 0;
}
From a brief look, the code snippet is an implementation of depth-first search, which is a basic search technique for directed graphs; the same approach works for breadth-first search. Note that apparently this implementation works only if there is only one connected component, otherwise the test must be performed for each connected component until a cycle is found.
That being said, the technique works by choosing one node at will and starting a recursive search there. Basically, if the search discovers a node that is in the stack, there must be a cycle, since it has been previously reached.
In the current implementation, recStack is not actually the stack, it just indicates whether a specific node is currently in the stack, no sequence information is stored. The actual cycle is contained implicitly in the call stack. The cycle is the sequence of nodes for which the calls of isCyclicUtil has not yet returned. If the actual cycle has to be extracted, the implementation must be changed.
So essentailly, what this is saying, is if a node leads to itself, there is a cycle. This makes sense if you think about it!
Say we start at node1.
{node1 -> node2}
{node2 -> node3}
{node3 -> node4
node3 -> node1}
{node4 -> end}
{node1 -> node2}
{node2 -> node3}.....
This is a small graph that contains a cycle. As you can see, we traverse the graph, going from each node to the next. In some cases we reach and end, but even if we reach the end, our code wants to go back to the other branch off of node3 so that it can check it's next node. This node then leads back to node1.
This will happen forever if we let it, because the path starting at node1 leads back to itself. We are recursively putting each node we visit on the stack, and if we reach an end, we remove all of the nodes from the stack AFTER the branch. In our case, we would be removing node4 from the stack every time we hit the end, but the rest of the nodes would stay on the stack because of the branch off of node3.
Hope this helps!

Count number of cycles in directed graph using DFS

I want to count total number of directed cycles available in a directed graph (Only count is required).
You can assume graph is given as adjacency matrix.
I know DFS but could not make a working algorithm for this problem.
Please provide some pseudo code using DFS.
This algorithm based on DFS seems to work, but I don't have a proof.
This algorithm is modified from the dfs for topological sorting
(https://en.wikipedia.org/wiki/Topological_sorting#Depth-first_search).
class Solution {
vector<Edge> edges;
// graph[vertex_id] -> vector of index of outgoing edges from #vertex_id.
vector<vector<int>> graph;
vector<bool> mark;
vector<bool> pmark;
int cycles;
void dfs(int node) {
if (pmark[node]) {
return;
}
if (mark[node]) {
cycles++;
return;
}
mark[node] = true;
// Try all outgoing edges.
for (int edge_index : graph[node]) {
dfs(edges[edge_index].to);
}
pmark[node] = true;
mark[node] = false;
}
int CountCycles() {
// Build graph.
// ...
cycles = 0;
mark = vector<bool>(graph.size(), false);
pmark = vector<bool>(graph.size(), false);
for (int i = 0; i < (int) graph.size(); i++) {
dfs(i);
}
return cycles;
}
};
Let us consider that , we are coloring the nodes with three types of color . If the node is yet to be discovered then its color is white . If the node is discovered but any of its descendants is/are yet to be discovered then its color is grey. Otherwise its color is black . Now, while doing DFS if we face a situation when, there is an edge between two grey nodes then the graph has cycle. The total number of cycles will be total number of times we face the situation mentioned above i.e. we find an edge between two grey nodes .

Finding which parallel edge was used in a path in a BGL graph?

Can anyone show, with a working example, how one might determine the actual edges used by path obtained from an astar_search() on a graph of type: adjacency_list<multisetS,vecS,directedS,location,route> when parallel edges (multiple routes between the same adjacent source and target vertex) are likely to be present (with different "costs")?
location and route are custom structures that I have as bundled properties for vertices and edges.
I originally was going to use a listS (specifically a std::list) as the type for the outEdgesList but I understand that if I wanted to use out_edge_range(source, target, graph) to retrieve all the edges linking source and target, it needs to be a multisetS (an "ordered set" which permits duplicate values?) - in the worst case I would have to step back through the vertexes of the found path from destination to start, and use the current and previous vertexes with that to recall all the possible edges involved and then pick the one with the lowest "cost" - but that seems a bit non-optimal if the search has already done just that to find the path...!
I am led to believe an edge_predecessor_recorder visitor might be a way to note down the particular edge selected but I have not been able to find a code sample that shows it in use - can that particular visitor even be used on the predecessor map from an A* search?
I should say that I am not totally familiar with the boost libraries - and I'm not that strong on C++ (C: yes, C++: gulp !) The way that the BGL typedefs things and provides some data structures automagically may, indeed, maximise the flexibility to utilise it - but it is a little confusing for the inexperienced (me, for example) to pin down the actual types of elements used or needed for a particular use IMVHO.
I think you're on the right track. This worked for me:
struct location_t { // vertex properties
std::string name;
};
struct route_t { // edge properties
std::size_t distance;
};
typedef adjacency_list<listS,vecS,directedS,location_t,route_t> graph_t;
typedef graph_traits<graph_t>::edge_descriptor edge_t;
typedef graph_traits<graph_t>::vertex_descriptor vertex_t;
struct heuristic {
heuristic(vertex_t dest) : dest_(dest) {}
std::size_t operator()(vertex_t src) {
// only needs to be "optimistic", so:
return (src == dest_) ? 0 : 1 ;
}
private:
vertex_t dest_;
};
typedef std::map<vertex_t, edge_t> pred_edge_map_t;
typedef associative_property_map<pred_edge_map_t> pred_edge_pmap_t;
int main() {
graph_t g;
// insert four vertices and a mix of singular and parallel edges
vertex_t zero = add_vertex(location_t{"A"}, g); // source
vertex_t one = add_vertex(location_t{"B"}, g);
vertex_t two = add_vertex(location_t{"C"}, g);
vertex_t three = add_vertex(location_t{"D"}, g); // sink
// optimal path: 0->2->3 (cost 6)
add_edge(zero, one, route_t{3}, g);
add_edge(zero, one, route_t{5}, g); // parallel to previous edge
add_edge(zero, two, route_t{4}, g);
add_edge(one, three, route_t{4}, g);
add_edge(two, three, route_t{2}, g);
add_edge(two, three, route_t{4}, g); // parallel to previous edge
// construct predecessor map
pred_edge_map_t pred;
pred_edge_pmap_t pred_pmap(pred);
// construct visitor that uses it
auto recorder = record_edge_predecessors(pred_pmap, on_edge_relaxed());
astar_visitor<decltype(recorder)> visitor(recorder);
astar_search(g, zero, heuristic(three),
weight_map(get(&route_t::distance, g)).
visitor(visitor));
// extract route (in reverse order)
for (vertex_t v = three; v != zero; v = source(pred_pmap[v], g)) {
auto e = pred_pmap[v];
std::cout << g[source(e, g)].name << "->" << g[target(e, g)].name << " with weight " << g[pred_pmap[v]].distance << std::endl;
}
}

Resources