PathFinding algorithm within this implementation of a grid - algorithm

Reading about Dijkstra's algorithm for pathfinding, I see that every example applicable to a "grid based" game is related to the case in which you have a "cell" that is passable or not passable. I better examplain with an image:
I need to implement an algorithm for pathfinding from A to B (returning a list of Cells to "follow") for the case II. As you can see from the image, in this model there aren't cells which are "unpassable", but every cell has stored 4 informations that determines if, while inside a cell, you can go up, down, left, right.
Searching on the net I found a lot of implementations of Dijkstra's algorithm for Case I.
Is it possible to implement it for case II?
If yes, can you please give me an advice?
Should I use another algorithm for that case (The grid will be 32x14)?

Yes, it is possible. Transform your cells into a graph by modelling cells as nodes, and only connect two cells with an edge, if no wall separates them.
However, Dijkstra is not the best algorithm to use, for such an easy example. If all edges in the graph have a distance of one, you can simply use a BFS search to find the quickest path.
Additionally, the fact that the path is a grid may mean that you could even find faster algorithms to solve the problem. However, this only makes sense if your grid is really big. For your 32x14 grid, I highly doubt that a sophisticated algorithm will be faster than BFS.

Related

Reduce number of nodes in 3D A* pathfinding using (part of a) uniform grid representation

I am calculating pathfinding inside a mesh which I have build a uniform grid around. The nodes (cells in the 3D grid) close to what I deem a "standable" surface I mark as accessible and they are used in my pathfinding. To get alot of detail (like being able to pathfind up small stair cases) the ammount of accessible cells in my grid have grown quite large, several thousand in larger buildings. (every grid cell is 0.5x0.5x0.5 m and the meshes are rooms with real world dimensions). Even though I only use a fraction of the actual cells in my grid for pathfinding the huge ammount slows the algorithm down. Other than that it works fine and finds the correct path through the mesh, using a weighted manhattan distance heuristic.
Imagine my grid looks like that and the mesh is inside it (can be more or less cubes but its always cubical), however the pathfinding will not be calculated on all the small cubes just a few marked as accessible (usually at the bottom of the grid but that can depend on how many floors the mesh has).
I am looking to reduce the search space for the pathfinding... I have looked at clustering like how HPA* does it and other clustering algorithms like Markov but they all seem to be best used with node graphs and not grids. One obvious solution would be to just increase the size of the small cubes building the grid but then I would lose alot of detail in the pathfinding and it would not be as robust. How could I cluster these small cubes? This is how a typical search space looks when I do my pathfinding (blue are accessible, green is path):
and as you see there is a lot of cubes to search through because the distance between them is quite small!
Never mind that the grid is an unoptimal solution for pathfinding for now.
Does anyone have an idea on how to reduce the ammount of cubes in the grid I have to search through and how would I access the neighbors after I reduce the space? :) Right now it only looks at the closest neighbors while expanding the search space.
A couple possibilities come to mind.
Higher-level Pathfinding
The first is that your A* search may be searching the entire problem space. For example, you live in Austin, Texas, and want to get into a particular building somewhere in Alberta, Canada. A simple A* algorithm would search a lot of Mexico and the USA before finally searching Canada for the building.
Consider creating a second layer of A* to solve this problem. You'd first find out which states to travel between to get to Canada, then which provinces to reach Alberta, then Calgary, and then the Calgary Zoo, for example. In a sense, you start with an overview, then fill it in with more detailed paths.
If you have enormous levels, such as skyrim's, you may need to add pathfinding layers between towns (multiple buildings), regions (multiple towns), and even countries (multiple regions). If you were making a GPS system, you might even need continents. If we'd become interstellar, our spaceships might contain pathfinding layers for planets, sectors, and even galaxies.
By using layers, you help to narrow down your search area significantly, especially if different areas don't use the same co-ordinate system! (It's fairly hard to estimate distance for one A* pathfinder if one of the regions needs latitude-longitude, another 3d-cartesian, and the next requires pathfinding through a time dimension.)
More efficient algorithms
Finding efficient algorithms becomes more important in 3 dimensions because there are more nodes to expand while searching. A Dijkstra search which expands x^2 nodes would search x^3, with x being the distance between the start and goal. A 4D game would require yet more efficiency in pathfinding.
One of the benefits of grid-based pathfinding is that you can exploit topographical properties like path symmetry. If two paths consist of the same movements in a different order, you don't need to find both of them. This is where a very efficient algorithm called Jump Point Search comes into play.
Here is a side-by-side comparison of A* (left) and JPS (right). Expanded/searched nodes are shown in red with walls in black:
Notice that they both find the same path, but JPS easily searched less than a tenth of what A* did.
As of now, I haven't seen an official 3-dimensional implementation, but I've helped another user generalize the algorithm to multiple dimensions.
Simplified Meshes (Graphs)
Another way to get rid of nodes during the search is to remove them before the search. For example, do you really need nodes in wide-open areas where you can trust a much more stupid AI to find its way? If you are building levels that don't change, create a script that parses them into the simplest grid which only contains important nodes.
This is actually called 'offline pathfinding'; basically finding ways to calculate paths before you need to find them. If your level will remain the same, running the script for a few minutes each time you update the level will easily cut 90% of the time you pathfind. After all, you've done most of the work before it became urgent. It's like trying to find your way around a new city compared to one you grew up in; knowing the landmarks means you don't really need a map.
Similar approaches to the 'symmetry-breaking' that Jump Point Search uses were introduced by Daniel Harabor, the creator of the algorithm. They are mentioned in one of his lectures, and allow you to preprocess the level to store only jump-points in your pathfinding mesh.
Clever Heuristics
Many academic papers state that A*'s cost function is f(x) = g(x) + h(x), which doesn't make it obvious that you may use other functions, multiply the weight of the cost functions, and even implement heatmaps of territory or recent deaths as functions. These may create sub-optimal paths, but they greatly improve the intelligence of your search. Who cares about the shortest path when your opponent has a choke point on it and has been easily dispatching anybody travelling through it? Better to be certain the AI can reach the goal safely than to let it be stupid.
For example, you may want to prevent the algorithm from letting enemies access secret areas so that they avoid revealing them to the player, and so that they AI seems to be unaware of them. All you need to achieve this is a uniform cost function for any point within those 'off-limits' regions. In a game like this, enemies would simply give up on hunting the player after the path grew too costly. Another cool option is to 'scent' regions the player has been recently (by temporarily increasing the cost of unvisited locations because many algorithms dislike negative costs).
If you know what places you won't need to search, but can't implement in your algorithm's logic, a simple increase to their cost will prevent unnecessary searching. There's a lot of ways to take advantage of heuristics to simplify and inform your pathfinding, but your biggest gains will come from Jump Point Search.
EDIT: Jump Point Search implicitly selects pathfinding direction using the same heuristics as A*, so you may be able to implement heuristics to a small degree, but their cost function won't be the cost of a node, but rather, the cost of traveling between the two nodes. (A* generally searches adjacent nodes, so the distinction between a node's cost and the cost of traveling to it tends to break down.)
Summary
Although octrees/quad-trees/b-trees can be useful in collision-detection, they aren't as applicable to searches because they section a graph based on its coordinates; not on its connections. Layering your graph (mesh in your vocabulary) into super graphs (regions) is a more effective solution.
Hopefully I've covered anything you'll find useful.
Good luck!

How to tell when the A* algorithm is a good option, and how to choose a good heuristic?

Recently I wrote a solver for the famous "15 puzzle" using the A* algorithm by using a heuristic function based off the sum of the Manhattan distances of the distances for each tile to their destination spots.
This led me to wonder two things:
How do you know when the A* algorithm is even something to use? Unless I came across online tutorials, I would have never guessed that the 15 puzzle could be solved this way.
How do you know which heuristic function to use? At first, for the 15 puzzle, I considered a simple "sum of tiles not in position" heuristic. So if all pieces weren't in their right spots, the heuristic for the 15 puzzle might return 15, whereas 0 would indicate a solved board. But somehow the sum of the distances are better. How does one know, going into it?
If you're exploring a graph to find a path that is in some way "shortest" (the cost doesn't have to be a "distance", but it has to be monotone), you can already use Dijkstra's. Your problem will typically look nothing like path-finding at a first glance though, as in, you're not planning to "travel over a route". It's more abstract than that.
Then if you can use Dijkstra and you have some admissible heuristic (that's the hard part), you can use A*.
An often used technique for finding heuristics is dropping some constraint of your problem. For example, if you can teleport each tile to its destination regardless of whether there's already a tile there, it will take #displacements teleports. So there's the first heuristic. If you have to slide the tiles but they can slide through each other, the cost for each tile is the Manhattan distance to its destination. Then you can look at improving the heuristic, for example the Manhattan distance heuristic obviously ignores that tiles interfere with each other as they move, but there is a simple case where we know where tiles must conflict and use more moves: consider two tiles (pretend there are no other tiles) in the same row and their destinations are also on that row but in order to get there they'd have to pass through each other. They'd have to go around each other, adding two vertical moves. This gives the Linear Conflicts heuristic. Even more interference can be taken into account, for example with pattern databases.

thinning/skeletonization algorithm with 4 known neighbors

I am searching for a thinning/skeletonization algorithm which works if I only know 4 neighbors not 8.
From all algorithms I could find I assume that I have knowledge about the diagonal neighbors.
So does anybody know about a thinning algorithm which also works if I only know the top, right, bottom, left neighbor?
The outcome should be like this:
http://www.cs.ru.nl/~ths/rt2/col/h9/thinning.GIF
These are not what I am looking for:
http://upload.wikimedia.org/wikipedia/commons/thumb/9/93/Skel.png/220px-Skel.png
The shape should be maintained as in the first example
I'd suggest using one of the 8-neighbour algorithms, but feeding it dummy information for the diagonal cells or otherwise modifying the part of the algorithm that considers neighbours.
Since you're not too specific about the kinds of things you're looking at it's hard to offer concrete suggestions. Most algorithms will contain a part that looks like this:
for n in neighbours:
do stuff
in which case you need to edit neighbours.
Others will apply some kind of mask or kernel function. Edit that kernel.

Finding a maximal square from a finite set of tiles (approximation)

I have a final set of tiles in which every edge can have on of four colors.
The task is to find a maximal possible square build from a given set (finite) of this tiles. Tiles can be rotated.
I need to design 3 algorithms for finding a solution for this task. One complete and two aproximations.
Obviously it is my task for Algorithms class so Im not asking about complete solutions (as this would be unfair) but for some directions.
Im already designed a kind of complete algorithm (using backtracking - search for a square of size sqrt(n) - if it could not be found try finding smaller and so on) but I have no idea how to create aproximation algorithms. I think one will be kind of stupid which will find a good answer only in specific cases just to document that it is not a good aproach but still I need one much faster then backtracking and quite good one.
Also is this problem NP-hard one? My backtracking algorithm is exponential one but it doesnt mean that there cannot be a better one...
EDIT: I have complete algorithm with exponential time, could some one give me some hints how to build some kind of aproximation for this problem with polynomial time or something better then exponential?
EDIT2: I have the idea that this problem can be changed to a problem of reducting a graph to square grid graph ( http://mathworld.wolfram.com/GridGraph.html ). Still there is a problem if the tiles can be arranged in such a way to build a grid, but this could be a good point to start. Are there any, for example, greedy or any other aproximation algorithms for reducting graph to square-grid graph?
Suppose your backtracking algorithm constructs k-by-k squares for increasing values of k.
You can extend the backtracking algorithm with heuristics. So instead of choosing the next tile randomly, choose and attach a tile such that the colors of the free tiles "agree with" those on the square. The big problem is to find the "agreement" heuristics. One possible heuristics is to find the least common color on the free tiles and use it.

8-direction path finding algorithm

I'm having trouble finding the right pathfinding algorithm for some AI I'm working on.
I have players on a pitch, moving around freely (not stuck to a grid), but they are confined to moving in 8 directions (N NE E etc.)
I was working on using A*, and a graph for this. But I realised, every node on the graph is equally far apart, and all the edges have the same weight - since the pitch is rectangular. And the number of nodes is enormous (being a large pitch, with them able to move between 1 pixel and another)
I figured there must be another algorithm, optimised for this sort of thing?
I would break the pitch down into 10x10 pixel grid. Your routing does not have to be as finely grained as the rest of your system and it makes the algorithm take up far less memory.
As Chris suggests above, choosing the right heuristic is the key to getting the algorithm working right for you.
If players move in straight lines between points on your grid, you really don't need to use A*. Bresenham's line algorithm will provide a straight line path very quickly.
You could weight a direction based on another heuristic. So as opposed to weighting the paths based on actual distance you could weight or scale that based on another factor such as "closeness to another player" meaning players will favour routes that will not collide with other players.
The A* algorithm should work well like this.
I think you should try Jump Point Search. It is a very fast algorithm for path finding on 8-dire.
Here is a blog describing Jump Point Search shortly.
And, this is its academic paper <Online Graph Pruning for Pathfinding on Grid Maps>
Besides, there are some interesting videos on Youtube.
I hope this helps.

Resources