1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
|
#include <string>
#include <fstream>
#include <iostream>
#include <stack>
#include <vector>
#include <chrono>
#include <boost/lexical_cast.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>
int main()
{
using namespace boost;
typedef adjacency_list<listS, vecS, directedS, no_property,
property<edge_weight_t, int>> graph_t;
graph_t g;
std::ifstream f("test.txt");
std::vector<std::string> maze;
for(std::string line; f >> line;)
maze.push_back(line);
std::size_t nrows = maze.size();
std::size_t ncols = maze[0].size(); // todo check if all are the same
int target_pos = 0;
for(std::size_t row = 0; row < maze.size(); ++row)
for(std::size_t col = 0; col < maze[row].size(); ++col) {
// special cases
if(maze[row][col] == '|') continue; // wall
if(maze[row][col] == '$') { // goal
maze[row][col] = '0';
target_pos = row*ncols + col;
}
// the weight of this node
int w = lexical_cast<int>(maze[row][col]);
// edges leading to this location have the weight 'w'
if(row > 0 && maze[row-1][col] != '|')
get(edge_weight, g)[add_edge( (row-1) * ncols + col , row*ncols+col, g).first] = w;
if(row < nrows-1 && maze[row+1][col] != '|')
get(edge_weight, g)[add_edge( (row+1) * ncols + col , row*ncols+col, g).first] = w;
if(col > 0 && maze[row][col-1] != '|')
get(edge_weight, g)[add_edge( row * ncols + (col-1), row*ncols+col, g).first] = w;
if(col < ncols-1 && maze[row][col+1] != '|')
get(edge_weight, g)[add_edge( row * ncols + (col+1), row*ncols+col, g).first] = w;
}
std::cout << "Loaded the " << ncols << "x" << nrows << " maze as a graph with " << num_vertices(g) << " nodes\n";
// call Dijkstra
typedef graph_traits<graph_t>::vertex_descriptor vertex_descriptor;
std::vector<vertex_descriptor> p(num_vertices(g)); // predecessors
std::vector<int> d(num_vertices(g)); // distances
vertex_descriptor start = vertex(0, g); // starting point
vertex_descriptor goal = vertex(target_pos, g);
auto time_1 = std::chrono::high_resolution_clock::now();
dijkstra_shortest_paths(g, start, predecessor_map(&p[0]).distance_map(&d[0]));
auto time_2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> dur = time_2 - time_1;
// print the results
std::stack<vertex_descriptor> path;
for(vertex_descriptor v = goal; v != start; v = p[v])
path.push(v);
path.push(start);
std::cout << "Total weight of the shortest path: " << d[target_pos] << '\n'
<< "The number of steps: " << path.size() << '\n';
while(!path.empty()) {
int pos = path.top();
std::cout << '[' << pos / ncols << ',' << pos % ncols << "] ";
path.pop();
}
std::cout << "\nIt took " << dur.count() << " ms to calculate\n";
}
|