Heuristics and A* Pathfinding

By Patrick Lester ( Updated April 21, 2004)


This article is a sidebar for the main article, A* Pathfinding for Beginners.

As was noted in the main article, there are several ways that you can calculate the heuristic in A*. I describe a few here. You should also check out the links at the bottom of this page.

Manhattan Method

This is the method used in the main article. Its primary advantage is that it will generally get you to the target faster than most alternatives. Its primary drawback is that in a 8-way pathfinder like the one in the main example, this method is inadmissible, so it is not guaranteed to give us the shortest possible path. It will almost always give the shortest path, though, and when it doesn't it won't be far off. Also, because it is overweighted compared to G, it will overpower any small modifiers that you try to add to the calculation of G like, say, a turning penalty or an influence map modifier. If you don't have those, this method is probably your best bet. The equation, where abs = absolute value, is:

H = 10*(abs(currentX-targetX) + abs(currentY-targetY))

Diagonal Shortcut

This method balances H with G. Its primary advantage is that, because it is balanced, it is able to fully consider small modifiers like a turning penalty or influence map modifier. It is also admissible. It is a bit slower than the Manhattan method, though. The equation, where abs = absolute value, is:

xDistance = abs(currentX-targetX)
yDistance = abs(currentY-targetY)
if xDistance > yDistance
H = 14*yDistance + 10*(xDistance-yDistance)
else
H = 14*xDistance + 10*(yDistance-xDistance)
end if

There are many other methods for calculating H, although these are probably two of the most commonly used. In general, the closer your estimate is to the actual remaining distance along the path to the goal, the faster A* will find that goal. If you overestimate H compared to the actual remaining distance, however, A* is not guaranteed to give you the best path. The trick, then, is to come as close to the actual distance as possible, without overestimating.

For more information, see: