A heuristic function estimates the remaining cost from a search state to a goal. In a maze, it gives A* a way to favor locations that appear closer to the goal without first finding a complete route. section 2.2
For a location identified by row and column, two estimates are straight-line Euclidean distance and Manhattan distance. Manhattan distance adds the absolute row and column differences. It fits a maze whose moves cannot go diagonally, but it does not account for walls that force a detour. section 2.2
func manhattanDistance(ml: MazeLocation) -> Float {
let xdist = abs(ml.col - goal.col)
let ydist = abs(ml.row - goal.row)
return Float(xdist + ydist)
}
The Swift function turns row and column differences into a Float estimate that can be passed as A*’s heuristicFn. section 2.2
A* keeps each search node’s cost so far alongside its heuristic estimate. The node comparison uses their sum, allowing a priority queue to consider both progress already made and estimated distance still to go. For the maze, pass manhattanDistance as heuristicFn; a different heuristic can be supplied through the same parameter. section 2.2
