Distance measured along axes: . Grid movement, city blocks, and taxicab problems.
The rotation trick — the one thing to remember
— proved in Primitives. Rotating by 45° (and scaling by ) turns Manhattan into Chebyshev, which decouples the coordinates — and over independent coordinates is far easier to optimise than a sum of absolute values.
// transform
ll u = x + y, v = x - y;
// inverse
ll xback = (u + v) / 2, yback = (u - v) / 2; // exact iff u, v have the same parity (true whenever x, y are integers)Immediate consequences
| Problem | With the rotation |
|---|---|
| Maximum Manhattan distance among points | — |
| Maximum distance in dimensions | over sign patterns of — |
| Manhattan balls (diamonds) | become axis-aligned squares |
| Do two diamonds intersect? | do two squares intersect — trivial |
| Manhattan nearest neighbour | Chebyshev nearest neighbour |
| Points within Manhattan distance | points in a square |
Proof: the inverse transform is exact on integers
, gives and , so , — exact division whenever and are even, which holds automatically since is even by construction for any integer (and likewise ). So the round trip is lossless on the integer lattice: every arising from an integer recovers it exactly, with no rounding.
Chebyshev distance
— the number of king moves on a chessboard. The inverse rotation converts Chebyshev back to Manhattan.
Proof: king-move distance is Chebyshev
A king can change by and by in the same move, so each move reduces by at most 1 (both coordinates move toward the target simultaneously along the move that decreases the larger gap, or decreases both if equal) — giving moves needed. Exactly that many suffice: move diagonally while both gaps remain positive (reducing both by 1 per move), then move straight along the one remaining nonzero axis — reaching the target in exactly moves.
Sum of pairwise Manhattan distances
Because the coordinates are independent,
and each term is computed in by sorting:
ll sumAbsDiff(vector<ll> a) {
sort(a.begin(), a.end());
ll total = 0, pref = 0;
for (int i = 0; i < (int)a.size(); i++) {
total += (ll)i * a[i] - pref;
pref += a[i];
}
return total;
}This separability is the defining advantage of over , and it makes many “sum of distances” problems easy that would be intractable in Euclidean geometry.
Proof:
sumAbsDiffOnce sorted, (since in sorted order means , so the absolute value is just the difference). Fix : it contributes for each of the later elements subtracting it, and for each of the earlier elements it subtracts — net contribution summed differently than the code’s running form, but equivalently: processing left to right, at index every earlier element has already been paired once with as (since now), contributing — exactly the code’s increment — and summing this over all accounts for every pair with exactly once.
Tested against the brute-force double sum on random integer arrays.
Minimising the sum of distances
The point minimising is the coordinate-wise median — independently in and in . That is an (or with nth_element) answer, whereas the Euclidean version (the geometric median) has no closed form.
Proof: the median minimises the sum of absolute deviations
For one coordinate, is piecewise linear and convex (a sum of convex functions). Its derivative where differentiable is (each term contributes or depending on which side of it’s on); this is negative while fewer than half the points are below , zero (or changes sign) once reaches the median, and positive beyond — so is minimised at any median (the middle element for odd , any value between the two middle elements for even ). Since the - and -sums are independent, minimising each coordinate’s median independently minimises the total .
For a weighted version, take the weighted median.
The Manhattan MST
The minimum spanning tree under has a beautiful algorithm:
For each point, only its nearest neighbour in each of 8 octants can be an MST edge.
So sweep in 4 directions (each covering 2 octants by symmetry), using a BIT to find the nearest candidate, producing candidate edges; then run Kruskal.
Proof: only the nearest neighbour per octant can be an MST edge
Partition the plane around a point into 8 octants of each (e.g. bounded by the axes and the two diagonals through ). Within one fixed octant, for any two points both in it (relative to ), one of or vice versa implies a triangle inequality shortcut: in the octant where, say, relative to for both and , Manhattan distance equals , which coincides with a simpler monotone relationship — specifically, if is the closer of the two to in this octant, then (the closer point , lying “between” and the octant’s far reaches in both coordinate senses, is never farther from than is). So in any spanning tree, an edge from directly to the farther point in that octant can be replaced by (both edges no longer than ) without increasing total weight — making the direct edge to anything but the nearest point in each octant redundant for a minimum spanning tree. Hence it suffices to consider, for every point, its nearest neighbour in each of the 8 octants: candidate edges in total, sufficient to contain a minimum spanning tree (by the standard cut-property argument: a true MST edge not among these candidates could always be shortened by routing through the relevant nearest neighbour, contradicting minimality).
instead of on the complete graph. The Euclidean analogue needs Delaunay; the Manhattan one needs only sorting and a BIT, which makes it considerably more approachable.
Where Manhattan geometry appears
| Problem | Note |
|---|---|
| Grid movement (4 directions) | distance = |
| King moves | distance = |
| VLSI routing | wires run along axes |
| Warehouse / facility placement | median minimises total travel |
| Taxicab problems | the name |
| ”Rotate the grid 45°” puzzles | the transformation above |
| Rectilinear Steiner tree | NP-hard, unlike the MST |
| Rectangle union / stabbing | axis-aligned throughout |
Diagonal movement
On a grid where diagonal moves also cost 1, the distance is Chebyshev. If diagonals cost (or 1.5 as in some game engines), the distance is the “octile” metric
which is the standard admissible heuristic for grid A*.
Proof: the octile distance formula
Write , . The optimal path takes diagonal moves (covering in both axes at once, cost ) followed by straight moves along the remaining axis (cost ) — total , matching the formula. This is optimal because diagonal moves are strictly more “efficient” per unit of -progress whenever both axes still have remaining distance to cover (a diagonal move advances both coordinates for one unit of cost , versus two straight moves costing to achieve the same net advancement in both axes), so using as many diagonals as possible (i.e. of them, until the shorter axis is exhausted) minimises total cost.