diff options
-rw-r--r-- | DijkstraPathfinder.cpp | 30 | ||||
-rw-r--r-- | DijkstraPathfinder.h | 4 |
2 files changed, 15 insertions, 19 deletions
diff --git a/DijkstraPathfinder.cpp b/DijkstraPathfinder.cpp index 95291b3..2fb07f5 100644 --- a/DijkstraPathfinder.cpp +++ b/DijkstraPathfinder.cpp @@ -19,7 +19,8 @@ void DijkstraPathfinder::find_between(const XY & start, const XY & end) { this->clear(); this->end = end; - this->explore(start); + this->map_get(start).distance = 0; + this->dijkstra(start); // no solution if (!this->is_visited(end)) return; @@ -37,11 +38,10 @@ DijkstraPathfinder::Node & DijkstraPathfinder::map_get(const XY & pos) { return this->map[pos]; } -void DijkstraPathfinder::explore(const XY & here, unsigned int cost) { - if (this->is_visited(here)) return; - +void DijkstraPathfinder::dijkstra(const XY & here) { + this->set_visited(here); PathfindingContext & ctx = this->museum.pathfinding; - unsigned int end_cost = this->map_get(this->end).cost; + unsigned int dist_end = this->map_get(this->end).distance; vector<pair<unsigned int, XY>> neighbors; vector<XY> offsets = { @@ -56,28 +56,24 @@ void DijkstraPathfinder::explore(const XY & here, unsigned int cost) { Tile & neighbor_tile = this->museum.canvas.get_tile(neighbor); unsigned int neighbor_cost = ctx.get_weight(neighbor_tile.data.type); - unsigned int step_cost = cost + neighbor_cost; + unsigned int dist_neighbor = this->map_get(here).distance + neighbor_cost; - if (step_cost > end_cost) continue; - - neighbors.push_back({ step_cost, neighbor }); + if (dist_neighbor >= dist_end) continue; Node & neighbor_node = this->map_get(neighbor); - if (step_cost < neighbor_node.cost) { - neighbor_node.parent = here; - neighbor_node.cost = step_cost; - } - } + if (dist_neighbor >= neighbor_node.distance) continue; - this->set_visited(here); + neighbor_node.parent = here; + neighbor_node.distance = dist_neighbor; + neighbors.push_back({ dist_neighbor, neighbor }); + } // sort by cost ascending sort(neighbors.begin(), neighbors.end(), [] (auto & left, auto & right) { return left.first < right.first; }); - for (pair<unsigned int, XY> & neighbor : neighbors) { - this->explore(neighbor.second, neighbor.first); + this->dijkstra(neighbor.second); } } diff --git a/DijkstraPathfinder.h b/DijkstraPathfinder.h index d02d9cb..eddb26f 100644 --- a/DijkstraPathfinder.h +++ b/DijkstraPathfinder.h @@ -19,12 +19,12 @@ private: XY end; struct Node { + unsigned int distance = -1; XY parent; - unsigned int cost = -1; }; Node & map_get(const XY &); std::unordered_map<XY, Node> map; - void explore(const XY &, unsigned int cost = 0); + void dijkstra(const XY &); }; |