Hi I am pretty new to the Boost libraries. I want to build a graph from a square two dimensional map that will be used for a star algorithm (the map is an array with 1s and 0s for both wall and normal terrain).
The graph should be undirected and change with the size of the map. Each node has 8 edges (except for sides of the map).
I've gone through a few examples but I don't understand the procedure for building graphs of this size since most examples look like this (look bellow) in the boost graph library documentation.
Any help or ideas will be really appreciated
#include <iostream> // for std::cout
#include <utility> // for std::pair
#include <algorithm> // for std::for_each
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>
using namespace boost;
int main(int,char*[])
{
// create a typedef for the Graph type
typedef adjacency_list<vecS, vecS, bidirectionalS> Graph;
// Make convenient labels for the vertices
enum { A, B, C, D, E, N };
const int num_vertices = N;
const char* name = "ABCDE";
// writing out the edges in the graph
typedef std::pair<int, int> Edge;
Edge edge_array[] =
{ Edge(A,B), Edge(A,D), Edge(C,A), Edge(D,C),
Edge(C,E), Edge(B,D), Edge(D,E) };
const int num_edges = sizeof(edge_array)/sizeof(edge_array[0]);
// declare a graph object
Graph g(num_vertices);
// add the edges to the graph object
for (int i = 0; i < num_edges; ++i){
add_edge(edge_array[i].first, edge_array[i].second, g);
}
return 0;
}
On second reading of the question it seems like your question is simply how to add nodes and edges.
Here's a start that queries for the number of rows/columns and creates the square "grid". I use a nodes matrix on the side to have easy lookup from (x,y) in the grid to the vertex descriptor in the graph.
Live On Coliru
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graph_utility.hpp>
#include <iostream>
using namespace boost;
struct Point {
int x, y;
friend std::ostream& operator<<(std::ostream& os, Point p) {
return os << "[" << p.x << "," << p.y << "]";
}
};
int main() {
using std::vector;
using Graph = adjacency_list<setS, vecS, undirectedS, Point>;
using vertex_descriptor = Graph::vertex_descriptor;
Graph lattuce;
int num_rows;
if (!(std::cin >> num_rows && num_rows > 0))
return 255;
vector<vector<vertex_descriptor> > nodes(num_rows, vector<vertex_descriptor>(num_rows));
for (auto i = 0; i < num_rows; ++i)
for (auto j = 0; j < num_rows; ++j)
nodes[i][j] = add_vertex(Point{i,j}, lattuce);
auto is_valid = [num_rows](Point p) { return (p.x >= 0 && p.x < num_rows) &&
(p.y >= 0 && p.y < num_rows); };
for (auto vd : make_iterator_range(vertices(lattuce))) {
auto p = lattuce[vd];
for (Point neighbour : {
Point { p.x - 1, p.y - 1 }, Point { p.x - 1, p.y + 0 }, Point { p.x - 1, p.y + 1 },
Point { p.x + 0, p.y - 1 }, Point { p.x + 0, p.y + 1 },
Point { p.x + 1, p.y - 1 }, Point { p.x + 1, p.y + 0 }, Point { p.x + 1, p.y + 1 },
})
{
if (is_valid(neighbour))
add_edge(nodes[neighbour.x][neighbour.y], vd, lattuce);
};
}
print_graph(lattuce, get(vertex_bundle, lattuce));
}
Prints, e.g. for input 3:
[0,0] <--> [0,1] [1,0] [1,1]
[0,1] <--> [0,0] [0,2] [1,0] [1,1] [1,2]
[0,2] <--> [0,1] [1,1] [1,2]
[1,0] <--> [0,0] [0,1] [1,1] [2,0] [2,1]
[1,1] <--> [0,0] [0,1] [0,2] [1,0] [1,2] [2,0] [2,1] [2,2]
[1,2] <--> [0,1] [0,2] [1,1] [2,1] [2,2]
[2,0] <--> [1,0] [1,1] [2,1]
[2,1] <--> [1,0] [1,1] [1,2] [2,0] [2,2]
[2,2] <--> [1,1] [1,2] [2,1]
Related
Per the documentation, the minimum spanning tree algorithm implemented in boost should work only on undirected graphs. Yet, the following code that provides a directed graph as input to the algorithm seems to work just fine: (while building on MSVC Visual Studio 2019, there are no warnings related to boost)
#include <boost/property_map/property_map.hpp>
#include <boost/config.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/kruskal_min_spanning_tree.hpp>
#include <boost/graph/graph_utility.hpp>
using namespace boost;
typedef adjacency_list <vecS, vecS, directedS, no_property,
property<edge_weight_t, double>>
Graph_vvd_MST;
typedef adjacency_list_traits<vecS, vecS, directedS> Traits_vvd;
property_map<Graph_vvd_MST, edge_weight_t>::type cost;
typedef Traits_vvd::edge_descriptor Edge;
std::vector < Edge > spanning_tree;
int main() {
Graph_vvd_MST g;
add_vertex(g);//0 th index vertex
add_vertex(g);// 1 index vertex
add_vertex(g);// 2 index vertex
cost = get(edge_weight, g);
//Add directed arcs
for(int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++) {
if (i == j)
continue;
std::pair<Traits_vvd::edge_descriptor, bool> AE = add_edge(i, j, g);
assert(AE.second);
if (i == 0 && j == 1) cost[AE.first] = 1;
if (i == 0 && j == 2) cost[AE.first] = 2;
if (i == 1 && j == 0) cost[AE.first] = 1;
if (i == 1 && j == 2) cost[AE.first] = 2;
if (i == 2 && j == 0) cost[AE.first] = 1;
if (i == 2 && j == 1) cost[AE.first] = 2;
}
kruskal_minimum_spanning_tree(g, std::back_inserter(spanning_tree));
printf("MST Solution:\n");
for (std::vector < Edge >::iterator ei = spanning_tree.begin();
ei != spanning_tree.end(); ++ei) {
int fr = source(*ei, g);
int to = target(*ei, g);
double cst = cost[*ei];
printf("[%d %d]: %f \n", fr, to, cst);
}
getchar();
}
The code above generates the following bidirectional graph:
The output of the code is correctly:
MST Solution:
[0 1]: 1.000000
[2 0]: 1.000000
Is it the case that the document is not updated and in recent boost versions, the algorithm can actually work with directed graphs?
I'd simplify the code Live
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/kruskal_min_spanning_tree.hpp>
#include <iostream>
using Graph =
boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS,
boost::no_property,
boost::property<boost::edge_weight_t, double>>;
using Edge = Graph::edge_descriptor;
int main()
{
Graph g(3); // 0..2
/*auto [it, ok] =*/ add_edge(0, 1, {1}, g);
add_edge(0, 2, {2}, g);
add_edge(1, 0, {1}, g);
add_edge(1, 2, {2}, g);
add_edge(2, 0, {1}, g);
add_edge(2, 1, {2}, g);
auto cost = get(boost::edge_weight, g);
std::vector<Edge> spanning_tree;
kruskal_minimum_spanning_tree(g, std::back_inserter(spanning_tree));
std::cout << "MST Solution:\n";
for (auto e : spanning_tree) {
std::cout << e << ": " << cost[e] << "\n";
}
}
If you insist on a loop to insert edges: Live
for (auto [i, j, c] : { std::tuple //
{0, 1, 1.},
{0, 2, 2.},
{1, 0, 1.},
{1, 2, 2.},
{2, 0, 1.},
{2, 1, 2.},
})
{
if (!add_edge(i, j, {c}, g).second)
return 255;
}
The Question
If you don't meet the documented pre-conditions the output is unspecified. Unspecified doesn't mean it throws an exception (that would be specified). It might even accidentally (seem to) do the right thing.
The point is that the algorithm operates under the assumption that edges are - by definition - traversable in the reverse direction at the same cost. As soon as you deviate from that, the algorithm may give incorrect results. In fact, some algorithms might exhibit undefined behaviour (like, a Dijkstra with some weights negative might never complete).
You'd do better to
Either convert your graph to be undirected
satisfy the invariants of undirected graphs and verify that the algorithm works correctly for it
Use an algorithm for MDST (Minimum Directed Spanning Tree), see e.g. Finding a minimum spanning tree on a directed graph
For special values like NA or NaN, boost::unordered_map creates a new key each time I use insert.
// [[Rcpp::depends(BH)]]
#include <boost/unordered_map.hpp>
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
void test_unordered_map(NumericVector vec) {
boost::unordered_map<double, int> mymap;
int n = vec.size();
for (int i = 0; i < n; i++) {
mymap.insert(std::make_pair(vec[i], i));
}
boost::unordered_map<double, int>::iterator it = mymap.begin(), end = mymap.end();
while (it != end) {
Rcout << it->first << "\t";
it++;
}
Rcout << std::endl;
}
/*** R
x <- c(sample(10, 100, TRUE), rep(NA, 5), NaN) + 0
test_unordered_map(x)
*/
Result:
> x <- c(sample(10, 100, TRUE), rep(NA, 5), NaN)
> test_unordered_map(x)
nan nan nan nan nan nan 4 10 9 5 7 6 2 3 1 8
How do I create only one key for NA and one for NaN?
bartop's idea of using a custom comperator is good, although the particular form did not work for me. So I used Boost's documentation as starting point. Combined with suitable functions from R I get:
// [[Rcpp::depends(BH)]]
#include <boost/unordered_map.hpp>
#include <Rcpp.h>
using namespace Rcpp;
struct R_equal_to : std::binary_function<double, double, bool> {
bool operator()(double x, double y) const {
return (R_IsNA(x) && R_IsNA(y)) ||
(R_IsNaN(x) && R_IsNaN(y)) ||
(x == y);
}
};
// [[Rcpp::export]]
void test_unordered_map(NumericVector vec) {
boost::unordered_map<double, int, boost::hash<double>, R_equal_to> mymap;
int n = vec.size();
for (int i = 0; i < n; i++) {
mymap.insert(std::make_pair(vec[i], i));
}
boost::unordered_map<double, int>::iterator it = mymap.begin(), end = mymap.end();
while (it != end) {
Rcout << it->first << "\t";
it++;
}
Rcout << std::endl;
}
/*** R
x <- c(sample(10, 100, TRUE), rep(NA, 5), NaN) + 0
test_unordered_map(x)
*/
Result:
> x <- c(sample(10, 100, TRUE), rep(NA, 5), NaN) + 0
> test_unordered_map(x)
7 2 nan nan 4 6 9 5 10 8 1 3
As desired, NA and NaN are inserted only once. However, one cannot differentiate between them in this output, since R's NA is just a special form of an IEEE NaN.
According to the IEEE standard, NaN values compared with == to anything yeilds always false. So, You just cannot do it this way. You can provide Your own comparator for unordered_map using this std::isnan function.
auto comparator = [](auto val1, auto val2) {
return std::isnan(val1) && std::isnan(val2) || val1 == val2;
}
boost::unordered_map<double, int, boost::hash<double>, decltype(comparator)> mymap(comparator);
I wrote the following code to implement the Dijkstra's shortest path algorithm:
#include <iostream>
#include <queue>
#include <utility>
#include <vector>
#include <functional>
#include <list>
#include <cstring>
int findPath(std::vector<std::list<std::pair<int, int>>> graph, int x, int y) {
int n = graph.size();
std::priority_queue < std::pair<int, int>, std::vector<std::pair<int, int>>, std::greater<std::pair<int, int>>> pq;
pq.push(std::pair<int, int>(0, x));
int *visited = new int[n + 1]{};
int *distance = new int[n + 1];
memset(distance, -1, sizeof(*distance) * (n + 1));
distance[x] = 0;
int current;
while (!pq.empty()) {
current = pq.top().second;
pq.pop();
if (current == y) {
return distance[y];
}
if (!visited[current]) {
visited[current] = 1;
for (std::list<std::pair<int, int>>::iterator it = graph[current].begin(); it != graph[current].end(); it++) {
if (!visited[it->first]) {
if (distance[it->first] == -1 || distance[it->first] > distance[current] + it->second) {
distance[it->first] = distance[current] + it->second;
pq.push(std::pair<int, int>(distance[it->first], it->first));
}
}
}
}
}
return distance[y];
}
int main()
{
std::ios::sync_with_stdio(false);
int n;
int m;
int x;
int y;
std::cin >> n >> m >> x >> y;
int a;
int b;
int c;
std::vector<std::list<std::pair<int, int>>> graph(n + 1);
for (int i = 0; i < m; ++i) {
std::cin >> a >> b >> c;
graph[a].push_back(std::pair<int, int>(b, c));
}
std::cout << findPath(graph, x, y) << std::endl;
return 0;
}
The input is N - number of vertexes, M - number of edges, x, y - 2 vertexes.
Then you have M lines of a, b, c which implies that you have a path from a to b with distance c.
Also you can have multiple edges from one vertex to another.
The goal is to find the shortest path from x to y. (-1 if there is no path)
I am using a priority queue of pairs (first one is the current distance to the vertex, and the second is the vertex).
The code works for some tests and gives a wrong answer for the rest (its from a judge system, so I can't see what the tests are).
I looked at it for an hour and I can't seem to find why it is not working.
I would be grateful if you can find the mistake, and why is it not working.
A sample input:
5 5 1 5
1 2 1
1 3 2
2 4 4
3 4 4
4 5 5
Output:
10
EDIT: There seems to be no error in the code. The task was ambiguous in the way that if there is a path from a to b, there is one from b to a. That was the error.
I have a really specified problem to deal with. I need to descending sort an array[4][x].
From instance if i get values like:
{121,120,203,240}
{0.5,0.2,3.2,1.4}
{1.3,1.5,1.2,1.8}
{3 ,2 ,5 ,4 }
All values have to bo sorted by the 4th row. Thus, I need an output like this:
{203,240,121,120}
{3.2,1.4,0.5,0.2}
{1.2,1.8,1.3,1.5}
{5 ,4 ,3 ,2 }
I have tried doing it by the bubble sort method, but it does not work properly.
A straightforward approach of sorting the array using the bubble sort can look the following way
#include <iostream>
#include <iomanip>
#include <utility>
int main()
{
const size_t N = 4;
double a[][N] =
{
{ 121, 120, 203, 240 },
{ 0.5, 0.2, 3.2, 1.4 },
{ 1.3, 1.5, 1.2, 1.8 },
{ 3, 2, 5, 4 }
};
for (const auto &row : a)
{
for (double x : row) std::cout << std::setw( 3 ) << x << ' ';
std::cout << '\n';
}
std::cout << std::endl;
// The bubble sort
for (size_t n = N, last = N; not (n < 2); n = last)
{
for (size_t i = last = 1; i < n; i++)
{
if (a[N - 1][i - 1] < a[N - 1][i])
{
for (size_t j = 0; j < N; j++)
{
std::swap(a[j][i - 1], a[j][i]);
}
last = i;
}
}
}
for (const auto &row : a)
{
for (double x : row) std::cout << std::setw( 3 ) << x << ' ';
std::cout << '\n';
}
std::cout << std::endl;
return 0;
}
The program output is
121 120 203 240
0.5 0.2 3.2 1.4
1.3 1.5 1.2 1.8
3 2 5 4
203 240 121 120
3.2 1.4 0.5 0.2
1.2 1.8 1.3 1.5
5 4 3 2
All you need is to extract the code of the bubble sort from main and rewrite it as a separate function for any 2D array and any row used as the criteria of sorting.
The problem would be easy to solve if instead of parallel vectors we had a structure containing parallel values.
It is easy enough to get back to such a structure: just create some intermediate vector containing sort keys and indexes and sort it.
After sorting the indexes are giving us a direct way to reorder all the individual vectors in the right order.
I would do something like below (I put it in a Boost Unit Test, but what is done should be obvious) .
#define BOOST_AUTO_TEST_MAIN
#define BOOST_TEST_MODULE TestPenta
#include <boost/test/auto_unit_test.hpp>
#include <iostream>
#include <vector>
std::vector<int> v1 = {121,120,203,240};
std::vector<float> v2 = {0.5,0.2,3.2,1.4};
std::vector<float> v3 = {1.3,1.5,1.2,1.8};
std::vector<int> v4 = {3 ,2 ,5 ,4 };
std::vector<int> expected_v1 = {203,240,121,120};
std::vector<float> expected_v2 = {3.2,1.4,0.5,0.2};
std::vector<float> expected_v3 = {1.2,1.8,1.3,1.5};
std::vector<int> expected_v4 = {5 ,4 ,3 ,2 };
BOOST_AUTO_TEST_CASE(TestFailing)
{
// First create an index to sort containing sort key and initial position
std::vector<std::pair<int,int>> vindex{};
int i = 0;
for (auto x: v4){
vindex.push_back(std::pair<int,int>(x,i));
++i;
}
// Sort the index vector by key value
struct CmpIndex {
bool operator() (std::pair<int, int> & a, std::pair<int, int> & b) {
return a.first > b.first ;
}
} cmp;
std::sort(vindex.begin(), vindex.end(), cmp);
// Now reorder all the parallel vectors using index
// (of course in actual code we would write some loop if several vector are of the same type).
// I'm using parallel loops to avoid using too much memory for intermediate vectors
{
std::vector<int> r1;
for (auto & p: vindex){
r1.push_back(v1[p.second]);
}
v1 = r1;
}
{
std::vector<float> r2;
for (auto & p: vindex){
r2.push_back(v2[p.second]);
}
v2 = r2;
}
{
std::vector<float> r3;
for (auto & p: vindex){
r3.push_back(v3[p.second]);
}
v3 = r3;
}
{
std::vector<int> r4;
for (auto & p: vindex){
r4.push_back(v4[p.second]);
}
v4 = r4;
}
// Et voila! The vectors are all sorted as expected
i = 0;
for (int i = 0 ; i < 4 ; ++i){
BOOST_CHECK_EQUAL(expected_v1[i], v1[i]);
BOOST_CHECK_EQUAL(expected_v2[i], v2[i]);
BOOST_CHECK_EQUAL(expected_v3[i], v3[i]);
BOOST_CHECK_EQUAL(expected_v4[i], v4[i]);
++i;
}
}
So I've got a homework problem:
Let G be a directed graph on n vertices.
Call G sortable if the vertices can be distinctly numbered from 1 to n (no two vertices have the same number) such that each vertex with incoming edges has at least one predecessor with a lower number. For example, Let NUM(v) be the number assigned to vertex v and consider a vertex x with incoming edges from three other vertices r, y, and z. Then NUM(x) must be bigger than at least one of NUM(r), NUM(y), and NUM(z).
Furthermore the algorithm must be linear; O(|V|+|E|).
Traversing the graph is easy enough but I have no idea how to check the parents of the vertex to see if the num of any of the parents are lower than that of the child.
How should I keep reference of the parents of the vertex I'm on?
The following adjacency lists are input files (Just samples the actual test cases have around 8k vertices).
1->2
2->3
3->1
Is not Sortable.
1->2
2->3
3->4
4->2
Is Sortable.
The problem can be in done in C++/C and I've chosen C++ for use of STL.
I store the graph using adjacency lists, the input files are edge lists.
Would this do it?
Create an adjacency matrix. If row points to col, then put a 1
there.
Scan down each col to the first 1. If col <= row then fail.
Otherwise, pass.
Here are the tables for your two examples:
1 2 3
1 0 1 0
2 0 0 1
3 1 0 0
1 2 3 4
1 0 1 0 0
2 0 0 1 0
3 0 0 0 1
4 0 1 0 0
If you are worried about space because it has to handle 8k vertices, then you can use a sparse representation if you know the input is sparse. But really, I think 64M ints should not be cause for concern.
GCC 4.7.3: g++ -Wall -Wextra -std=c++0x sortable-graph.cpp
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
std::string trim(const std::string& str) {
std::string s;
std::stringstream ss(str);
ss >> s;
return s;
}
using graph = std::vector<std::vector<int>>;
graph read(std::istream& is) {
graph G;
std::vector<std::pair<int, int>> edges;
std::map<std::string, int> labels;
int max = -1;
// Assume input is a list of edge definitions, one per line. Each line is:
// "label -> label" where white space is optional, "->" is a literal, and
// "label" does not contain "->" or white space.
// This can be vastly simplified if we can assume sensible int labels.
std::string l;
while (std::getline(is, l)) {
// Parse the labels.
const auto n = l.find("->");
const auto lhs = trim(l.substr(0, n));
const auto rhs = trim(l.substr(n + 2));
// Convert the labels to ints.
auto i = labels.find(lhs);
if (i == labels.end()) { labels[lhs] = ++max; }
auto j = labels.find(rhs);
if (j == labels.end()) { labels[rhs] = ++max; }
// Remember the edge.
edges.push_back({labels[lhs], labels[rhs]});
}
// Resize the adjacency matrix.
G.resize(max+1);
for (auto& v : G) { v.resize(max+1); }
// Mark the edges.
for (const auto& e : edges) { G[e.first][e.second] = 1; }
return G;
}
bool isSortable(const graph& G) {
const int s = G.size();
for (int col = 0; col < s; ++col) {
for (int row = 0; row < s; ++row) {
if (G[row][col] == 1) {
if (col <= row) { return false; }
break;
}
}
}
return true;
}
void print(std::ostream& os, const graph& G) {
const int s = G.size();
for (int row = 0; row < s; ++row) {
for (int col = 0; col < s; ++col) {
os << G[row][col] << " ";
}
os << "\n";
}
}
int main() {
const auto G = read(std::cin);
print(std::cout, G);
const auto b = isSortable(G);
std::cout << (b ? "Is Sortable.\n" : "Is not Sortable.\n");
}
Now that I look at it, I guess this is O(V^2).
Take two! This one is O(|V|+|E|).
GCC 4.7.3: g++ -Wall -Wextra -std=c++0x sortable-graph.cpp
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
std::string trim(const std::string& str) {
std::string s;
std::stringstream ss(str);
ss >> s;
return s;
}
using edges = std::vector<std::pair<int, int>>;
void read(std::istream& is, edges& E, int& max) {
std::map<std::string, int> labels;
max = -1;
// Assume input is a list of edge definitions, one per line. Each line is:
// "label -> label" where white space is optional, "->" is a literal, and
// "label" does not contain "->" or white space.
// This can be vastly simplified if we can assume sensible int labels.
std::string l;
while (std::getline(is, l)) {
// Parse the labels.
const auto n = l.find("->");
const auto lhs = trim(l.substr(0, n));
const auto rhs = trim(l.substr(n + 2));
// Convert the labels to ints.
auto i = labels.find(lhs);
if (i == labels.end()) { labels[lhs] = ++max; }
auto j = labels.find(rhs);
if (j == labels.end()) { labels[rhs] = ++max; }
// Remember the edge.
E.push_back({labels[lhs], labels[rhs]});
}
}
bool isSortable(const edges& E, int max) {
std::vector<int> num(max+1, max+1);
for (const auto& e : E) {
num[e.second] = std::min(e.first, num[e.second]);
}
for (int i = 0; i < num.size(); ++i) {
if (num[i] != max + 1 && i <= num[i]) { return false; }
}
return true;
}
int main() {
edges E;
int max;
read(std::cin, E, max);
const auto b = isSortable(E, max);
std::cout << (b ? "Is Sortable.\n" : "Is not Sortable.\n");
}