liveBook · Manning

Manhattan distance

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

Manhattan distance is the sum of the absolute differences between corresponding coordinates of two points.

Imagine crossing a city grid without diagonal streets: reaching a destination takes horizontal blocks plus vertical blocks. For two maze locations, Manhattan distance adds the absolute difference in their columns to the absolute difference in their rows. section 2.2

Count the required moves

From row 2, column 3 to row 5, column 7, the distance is |5 − 2| + |7 − 3| = 7 moves. Walls may force a longer route, but they cannot make this four-direction trip shorter. 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 computes those two absolute differences and returns their sum as a heuristic estimate to the goal. section 2.2

For a maze allowing only horizontal and vertical moves, this estimate never exceeds the actual remaining path length. A* can therefore use it while retaining an optimal solution; it follows the allowed movement more closely than straight-line Euclidean distance. section 2.2

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

How deep it goes
Defines the row-and-column calculation and implements it in Swift, then explains admissibility without a formal proof.
Examples
Uses Manhattan street blocks, maze locations, a grid figure, and a Swift distance function.
What it assumes
Assumes familiarity with Swift functions and row-and-column grid locations; introduces the distance through street navigation.
What you can do after
Build it from scratch as a Swift heuristic for four-direction A* maze search.
How it connects
Links grid movement, Euclidean distance, admissible heuristics, and A* search.

Also explained in

Compare how 4 books explain Manhattan distance →

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.