问题
I'm trying to create a simple grid-based game in C++. The pathfinding is necessary part of it. I've been searching, but there isn't what I am exactly looking for.
The rules are simple. There is a map. The size generally doesn't exceed 100 x 100 tiles. 1 is a floor tile, 0 is a wall. Diagonal movement isn't allowed, so there are only 4 directions from each grid. However there are mostly more than one goal. I'd like to find the way to nearest one. Remember that we can't just calculate, which one is the nearest by distance formula. The goal with shorter distance can has longer way, because of walls. I think using one of known algorithms and repeating, for each goal isn't a good idea, because it will slow.
What's your opinion? What should I do?
回答1:
This isn't a big problem. Add a hypothetical end node E with distance 1 to all real goals, and search the best path to E. The one-but-last node on the path will be one of those real goals.
回答2:
As stated by others. Consider encoding to graph and maybe best is to preacalculate this for all tiles. I would go basically for Floyd-Warshall algorithm. https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm
回答3:
A* is an algorithm that can be used to do pathfinding on 2D grids. Here's a good simple A* tutorial.
While you could run the algorithm several times, for each goal, an alternative would be to use an algorithm "Dijkstra's Algorithm", that unlike A* expands evenly in every direction, until all goals are found and select the one with the best result.
回答4:
A little trick that may help with this problem: Use A* to search from all goals simultaneously to the start and then reverse the path. It's simpler than calculating the minimum Manhattan distance to every goal in every step or adding extra nodes to the graph.
Since A* maintains a list of candidates for the least-cost path via the OPEN list, you can simply insert all goal tiles into that open list. Due to the open list being a priority queue, A* will then find the least-cost path from any of the goals by trying heuristically close goals first and only switching to goals that are further away once it becomes clear that the path to them is less costly. This gives you a path from the best goal to the start position, which you then simply reverse to get a path from start to goal.
来源:https://stackoverflow.com/questions/28840102/pathfinding-for-2d-tile-map-for-multiple-goals