liveBook · Manning

Heuristic function

As explained in Classic Computer Science Problems in Swift: Essential techniques for practicing programmers

A heuristic function estimates the remaining cost from a search state to a goal state.

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

How Classic Computer Science Problems in Swift: Essential techniques for practicing programmers covers it

How deep it goes
Implements Euclidean and Manhattan distance functions and plugs one into A*, without developing a formal accuracy proof.
Examples
Uses row-and-column distances in a four-direction maze and passes manhattanDistance to a Swift A* call.
What it assumes
Assumes familiarity with Swift functions and row-column locations while introducing the distance calculations through concrete code.
What you can do after
Build it from scratch as a Swift distance function and pass it to A* maze search.
How it connects
Links A*, priority queues, Manhattan distance, Euclidean distance, and shortest-path search.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Classic Computer Science Problems in Swift: Essential techniques for practicing programmers. The section links point to the parts of the book it draws on.