Algorithm Search⌘K

Algorithmcore

Hadlock's algorithm

Also called minimum detour routing.

A maze router that orders the search by detour number, the steps away from the target. It finds shortest paths and usually expands fewer cells than Lee's router.

Time
Θ(M N) worstΘ(1) best
Space
Θ(M N) extra
Where
M = the number of rows of the routing grid; N = the number of columns
Properties
deterministicexactiterative
Origin
F. O. Hadlock, 1977

Hadlock's algorithm is a maze router for electronic design automation (EDA) that finds a shortest path between two cells of a routing grid, like Lee's algorithm, but aims the search at the target. It labels each cell with its detour number, the least number of steps away from the target on a path from the source, and expands the cells in order of this number. The length of a path is the Manhattan distance between its ends plus twice its detours, so the path with the fewest detours is a shortest path. The search is A* search with the Manhattan distance as the heuristic, and on an open grid it expands far fewer cells than Lee's wave.

In plain words

Lee's router spreads out in all directions like a ring of water. Hadlock's router walks toward the goal as long as it can, and it only counts the steps that go the wrong way.

Each step either brings you one square nearer to the goal or takes you one square farther away. A step that takes you away is a detour. Every detour must be paid back later with one more step toward the goal. So a wire with dd detours is longer than the straight distance by exactly 2d2d squares.

The router first tries all squares it can reach with no detour. Then it tries those it can reach with one detour, then two, and so on. The first time it reaches the goal, it has used the fewest detours, so it has found a shortest wire.

The problem

The input is a grid of MM rows and NN columns, where each cell is free or blocked, and two free cells ss and tt. Moves go between free cells that share a side. The output is a shortest path from ss to tt, or the answer that no path exists. This is the problem of Lee's algorithm.

For cells uu and vv let md(u,v)=∣ur−vr∣+∣uc−vc∣\mathrm{md}(u, v) = |u_r - v_r| + |u_c - v_c| be the Manhattan distance between their row and column numbers. A step from uu to a neighbor vv is toward tt if md(v,t)=md(u,t)−1\mathrm{md}(v, t) = \mathrm{md}(u, t) - 1, and a detour if md(v,t)=md(u,t)+1\mathrm{md}(v, t) = \mathrm{md}(u, t) + 1. There is no third case. The detour number det(v)\mathrm{det}(v) is the least number of detours on a path from ss to vv.

The algorithm

  1. HADLOCK(grid, s, t)
  2. 1det(s) ← 0; deque ← [s]; done ← ∅
  3. 2while deque is not empty do
  4. 3u ← remove the first cell of deque
  5. 4if u ∈ done then continue
  6. 5add u to done
  7. 6if u = t then return the path from s to t by the parent links
  8. 7for each free neighbor v of u with v ∉ done do
  9. 8a ← 1 if md(v, t) > md(u, t), else 0
  10. 9if v has no label or det(u) + a < det(v) then
  11. 10det(v) ← det(u) + a; parent(v) ← u
  12. 11if a = 0 then add v at the front of deque else add v at the back
  13. 12return "no path"

Line L11 is a 0-1 BFS: a step toward the target costs 0 and goes to the front, a detour costs 1 and goes to the back. So the cells leave the deque in order of their detour number. Hadlock described the same order with a list of cells for each detour number.

Example

Take the grid of the Lee example, with s=(2,0)s = (2, 0) and t=(2,4)t = (2, 4), so md(s,t)=4\mathrm{md}(s, t) = 4. The second grid shows the detour labels when the search stops. A - is a free cell that never got a label.

. . . . .        2 2 2 2 2
. # # # .        1 # # # 2
s . . # t        0 0 0 # 2
# . # . .        # 1 # - -
. . . . .        - 2 - - -

The search expands the cells in this order:

detour number cells expanded
0 (2,0), (2,1), (2,2)
1 (1,0), (3,1)
2 (0,0), (0,1), (0,2), (0,3), (0,4), (1,4), (2,4)

From ss the search goes right with no detour until the wall at (2,3)(2, 3). The cells (1,0)(1, 0) and (3,1)(3, 1) cost one detour each, because they are one row away from the row of tt. From (1,0)(1, 0) the step up to (0,0)(0, 0) is a second detour. Then every step along the top row and down the right column goes toward tt, so these cells go to the front of the deque, and the search reaches tt with det(t)=2\mathrm{det}(t) = 2. The path is

(2,0),(1,0),(0,0),(0,1),(0,2),(0,3),(0,4),(1,4),(2,4)(2,0), (1,0), (0,0), (0,1), (0,2), (0,3), (0,4), (1,4), (2,4),

with length 4+2⋅2=84 + 2 \cdot 2 = 8, the same as Lee's. Hadlock expanded 12 cells. Lee's wave labeled all 19 free cells.

Correctness

The proof shows the following.

  • Length identity. A path from ss to a cell vv with DD detours has length md(s,t)−md(v,t)+2D\mathrm{md}(s, t) - \mathrm{md}(v, t) + 2D. For v=tv = t this is md(s,t)+2D\mathrm{md}(s, t) + 2D, so fewer detours means a shorter path.
  • Detour labels. The deque holds labels of two consecutive values, sorted from front to back. So each cell is expanded first with its true detour number, as in Dijkstra's algorithm with costs 0 and 1.
  • Shortest path. When tt is expanded, its label is det(t)\mathrm{det}(t), and the parent links give a path with this many detours, which by the identity is a shortest path.
  • A view.* For a path of length gg to vv, g+md(v,t)=md(s,t)+2Dg + \mathrm{md}(v, t) = \mathrm{md}(s, t) + 2D. So the order by detour number is the order of A* search with the consistent heuristic md(v,t)\mathrm{md}(v, t).
  • Completeness. If the deque empties before tt is expanded, every cell reachable from ss was expanded, so no path exists.
Proof: Hadlock's search expands cells in order of detour number, and the path with the fewest detours is a shortest pathfull

Let GG be the graph of free cells, with an edge between cells that share a side. For cells u,vu, v let md(u,v)\mathrm{md}(u, v) be the Manhattan distance of their coordinates. Let δ(v)\delta(v) be the length of a shortest path from ss to vv in GG and L=δ(t)L = \delta(t).

Lemma 1 (each step is toward or a detour). For neighbors u,vu, v, md(v,t)−md(u,t)∈{−1,+1}\mathrm{md}(v, t) - \mathrm{md}(u, t) \in \{-1, +1\}.

Proof. A step changes one coordinate by 1, so it changes one term of the Manhattan distance by exactly 1, and the other term not at all. □\square

Lemma 2 (length identity). Let PP be a path from ss to vv with TT toward steps and DD detours. Then its length is ∣P∣=T+D=md(s,t)−md(v,t)+2D|P| = T + D = \mathrm{md}(s, t) - \mathrm{md}(v, t) + 2D.

Proof. By Lemma 1, each toward step lowers md(⋅,t)\mathrm{md}(\cdot, t) by 1 and each detour raises it by 1. So md(v,t)=md(s,t)−T+D\mathrm{md}(v, t) = \mathrm{md}(s, t) - T + D, which gives T=md(s,t)−md(v,t)+DT = \mathrm{md}(s, t) - \mathrm{md}(v, t) + D and ∣P∣=T+D|P| = T + D. □\square

Corollary 3. For a fixed end vv, the length of a path is 2D2D plus a constant. So a path to vv has the fewest detours if and only if it is a shortest path, and δ(v)=md(s,t)−md(v,t)+2 det(v)\delta(v) = \mathrm{md}(s, t) - \mathrm{md}(v, t) + 2\,\mathrm{det}(v). In particular L=md(s,t)+2 det(t)L = \mathrm{md}(s, t) + 2\,\mathrm{det}(t). □\square

Let w(u,v)=1w(u, v) = 1 if the step from uu to vv is a detour and 0 otherwise. Then det(v)\mathrm{det}(v) is the least total weight of a path from ss to vv in the directed graph with these weights.

Lemma 4 (deque order). Consider each entry of the deque as the pair of a cell and the label it was given when it was added. At every moment the labels of the entries, from front to back, are non-decreasing, and the last is at most the first plus 1.

Proof. At the start the deque holds (s,0)(s, 0). Suppose the claim holds and line L3 removes the front entry, with label kk, the least label in the deque. If the cell is expanded, its label is kk, because a label only falls together with a new entry of the smaller value, and by the order that entry would have been removed first, making the cell done. Line L11 adds entries with label kk at the front and with label k+1k + 1 at the back. All labels in the deque were in {k,k+1}\{k, k + 1\}, so the order and the bound still hold. □\square

Lemma 5 (expanded labels are detour numbers). When a cell uu is expanded on line L5, det(u)\mathrm{det}(u) as stored equals its detour number, and the cells are expanded in non-decreasing order of it.

Proof. By Lemma 4 the labels of removed entries never decrease. This is the order of Dijkstra's algorithm with the non-negative weights ww, and the usual argument applies. Suppose uu is the first cell expanded with a stored label kk larger than its detour number k∗k^*. Take a path of weight k∗k^* from ss to uu, and let yy be its first cell that is not done when uu is expanded, with xx the cell before it. The cell xx is done, and by the choice of uu its label is its detour number. When xx was expanded, lines L9 and L10 gave yy a label of at most det(x)+w(x,y)≤k∗\mathrm{det}(x) + w(x, y) \le k^*, because the weights on the path are non-negative, and added an entry with that label. That entry is still in the deque, so by Lemma 4 it would be removed before the entry of uu with label k>k∗k > k^*, unless y=uy = u, in which case the stored label of uu is at most k∗k^*. Both cases contradict the choice of uu. □\square

Theorem (shortest path). If tt is reachable from ss, the search expands tt and returns a path with det(t)\mathrm{det}(t) detours. This path has length LL. If tt is not reachable, it returns "no path".

Proof. Every reachable cell gets an entry, since the neighbor of an expanded cell that is not done always gets one, and every entry is removed before the deque empties. So a reachable tt is expanded. By Lemma 5 its label is det(t)\mathrm{det}(t). The parent links satisfy det(v)=det(parent(v))+w(parent(v),v)\mathrm{det}(v) = \mathrm{det}(\mathrm{parent}(v)) + w(\mathrm{parent}(v), v) at the time each parent is set, and parents are only set to expanded cells, whose labels no longer change. Following them from tt gives a path from ss with exactly det(t)\mathrm{det}(t) detours. By Corollary 3 its length is md(s,t)+2 det(t)=L\mathrm{md}(s, t) + 2\,\mathrm{det}(t) = L. If tt is not reachable it never gets an entry, and line L12 is reached. □\square

Theorem (A view).* For a path of length gg from ss to vv with DD detours, g+md(v,t)=md(s,t)+2Dg + \mathrm{md}(v, t) = \mathrm{md}(s, t) + 2D. The heuristic h(v)=md(v,t)h(v) = \mathrm{md}(v, t) is consistent on GG, since h(u)≤1+h(v)h(u) \le 1 + h(v) for neighbors. So ordering by DD is ordering by the A* key g+hg + h.

Proof. The identity is Lemma 2 rearranged. Consistency is the triangle inequality of the Manhattan distance with md(u,v)=1\mathrm{md}(u, v) = 1. □\square

Lemma 6 (expanded cells are labeled by Lee). Every cell v≠tv \ne t that Hadlock expands has δ(v)<L\delta(v) < L, so Lee's wave, which labels all cells with δ(v)<L\delta(v) < L before it stops, labels vv.

Proof. By Lemma 5, vv is expanded before tt with det(v)≤det(t)\mathrm{det}(v) \le \mathrm{det}(t). By Corollary 3, δ(v)=md(s,t)−md(v,t)+2 det(v)≤L−md(v,t)<L\delta(v) = \mathrm{md}(s, t) - \mathrm{md}(v, t) + 2\,\mathrm{det}(v) \le L - \mathrm{md}(v, t) < L, since md(v,t)≥1\mathrm{md}(v, t) \ge 1 for v≠tv \ne t. □\square

Running time. Lines L4 and L5 expand each cell at most once. Each expansion looks at 4 neighbors and adds at most 4 entries. So there are at most 4MN+14MN + 1 entries and the time is O(MN)O(MN). The labels, parents and the deque take O(MN)O(MN) space. □\square

Complexity

  • Time. Lines L4 and L5 expand each cell at most once, and each expansion adds at most 4 entries to the deque. So there are at most 4MN+14MN + 1 entries, and the time is O(MN)O(MN). In the worst case, a maze that forces a long winding path, the search expands every cell, so the bound is Θ(MN)\Theta(MN).
  • Space. Labels, parents and the deque take Θ(MN)\Theta(MN) memory. The detour numbers need fewer bits than Lee's distances in practice, but they still grow with the grid.
  • Open grid. With no blockage between ss and tt, every cell on a monotone path has detour number 0, and the search walks straight to tt, expanding about md(s,t)\mathrm{md}(s, t) cells in our implementation, against about 2L22L^2 for Lee's wave.

Properties

  • What is proved. Hadlock's algorithm finds a shortest path whenever a path exists, and among the shortest paths it finds one with the fewest detours, which is the same thing. Every cell it expands has δ(s,v)+md(v,t)≤L\delta(s, v) + \mathrm{md}(v, t) \le L, where LL is the length of the shortest path, so every cell it expands is also labeled by Lee's wave.
  • What is measured. The inclusion above is about expanded cells. Hadlock also writes labels on the neighbors of expanded cells, and these can be more than the cells Lee labels. On 16386 random grids with a path from ss to tt (sizes 2 to 8 on each side, 10 to 40 percent blocked cells, Python random.Random(41)), Hadlock expanded fewer cells than Lee labeled in 15306 grids and never more, but it labeled more cells than Lee in 517 grids. These are toy inputs, not benchmark results.
  • Exact and deterministic. The front and back rule of line L11 fixes the order. Among cells of the same detour number, the most recent toward step is followed first, so the search runs straight on when it can.
  • One net at a time. As with Lee's router, the result is shortest for this net only, given the wires already placed.

Variants and improvements

  • Bucket lists. Hadlock kept a list of cells for each detour number. The deque of line L11 is the same idea with two lists, because labels in the deque differ by at most 1.
  • Weighted grids. With costs for vias, bends or congestion, the same aim at the target is A* search with the Manhattan distance times the least step cost as the heuristic.
  • Bidirectional search. Run detour searches from both ends, each aimed at the other end.
  • Soukup's search. Soukup's algorithm goes depth first toward the target and does not keep detour numbers. It is faster, but its path need not be shortest.

When to use it

  • To find a shortest path for a two-pin net on a grid that is large and mostly open, where Lee's wave would label many cells far from the target.
  • As the search step of a rip-up and reroute loop with unit costs.

With costs that are not uniform, use A* or Dijkstra's algorithm directly. When the grid is small, plain Lee's algorithm is simpler and just as fast.

Pitfalls

  • Detour from the source. The detour is measured against the target tt, not against ss. A step that goes away from ss but toward tt costs nothing.
  • Front and back mixed up. A toward step must go to the front and a detour to the back. The other way round, the cells leave in the wrong order and the path need not be shortest.
  • Stopping when tt is labeled. The search must stop when tt is expanded, not when it first gets a label. A first label can come through a detour, and a later toward step can lower it.
  • Old entries. A cell can be in the deque twice after its label falls. Line L4 skips the copies of cells that are already done.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

hadlock_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hadlock-algorithm/. The authors are listed in prov/Q7C4F1.jsonl.

from collections import deque
from typing import Optional, Sequence

Cell = tuple[int, int]

# Neighbor order: up, right, down, left.
STEPS = ((-1, 0), (0, 1), (1, 0), (0, -1))


def manhattan(a: Cell, b: Cell) -> int:
    return abs(a[0] - b[0]) + abs(a[1] - b[1])


def is_free(grid: Sequence[str], cell: Cell) -> bool:
    r, c = cell
    return 0 <= r < len(grid) and 0 <= c < len(grid[r]) and grid[r][c] != "#"


def hadlock_search(grid: Sequence[str], s: Cell, t: Cell) -> tuple[dict[Cell, int], dict[Cell, Cell], list[Cell]]:
    """Label cells with their least detour number from s, in order of detour number.

    A step is a detour if it moves away from t. Returns the detour labels,
    the parent of each labeled cell and the cells in the order they were expanded.
    The search stops when t is expanded.
    """
    det = {s: 0}
    parent: dict[Cell, Cell] = {}
    done: set[Cell] = set()
    order: list[Cell] = []
    dq = deque([s])  # @line L1
    while dq:  # @line L2
        u = dq.popleft()  # @line L3
        if u in done:  # @line L4
            continue
        done.add(u)  # @line L5
        order.append(u)
        if u == t:  # @line L6
            break
        for dr, dc in STEPS:  # @line L7
            v = (u[0] + dr, u[1] + dc)
            if not is_free(grid, v) or v in done:
                continue
            away = 1 if manhattan(v, t) > manhattan(u, t) else 0  # @line L8
            if v not in det or det[u] + away < det[v]:  # @line L9
                det[v] = det[u] + away  # @line L10
                parent[v] = u
                if away:  # @line L11
                    dq.append(v)
                else:
                    dq.appendleft(v)
    return det, parent, order


def hadlock_algorithm(grid: Sequence[str], s: Cell, t: Cell) -> Optional[list[Cell]]:
    """Return a path from s to t with the fewest detours, which is a shortest path, or None.

    grid is a list of equal-length strings, '#' marks a blocked cell. The path
    lists s first and t last. Its length is manhattan(s, t) + 2 * detours.
    """
    if not is_free(grid, s) or not is_free(grid, t):
        return None
    det, parent, order = hadlock_search(grid, s, t)
    if not order or order[-1] != t:  # @line L12
        return None
    path = [t]
    while path[-1] != s:
        path.append(parent[path[-1]])
    path.reverse()
    return path
test_hadlock_algorithm.py 80 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hadlock-algorithm/. The authors are listed in prov/Q7C4F1.jsonl.

import random

from hadlock_algorithm import hadlock_algorithm, hadlock_search, manhattan


def bfs_dist(grid: list[str], s: tuple[int, int]) -> dict[tuple[int, int], int]:
    """Plain breadth-first search over all free cells, written apart from the router."""
    rows, cols = len(grid), len(grid[0])
    dist = {s: 0}
    frontier = [s]
    while frontier:
        nxt = []
        for r, c in frontier:
            for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
                if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == "." and (nr, nc) not in dist:
                    dist[(nr, nc)] = dist[(r, c)] + 1
                    nxt.append((nr, nc))
        frontier = nxt
    return dist


def is_path(grid: list[str], path: list[tuple[int, int]], s: tuple[int, int], t: tuple[int, int]) -> bool:
    if path[0] != s or path[-1] != t:
        return False
    if any(grid[r][c] != "." for r, c in path):
        return False
    return all(manhattan(a, b) == 1 for a, b in zip(path, path[1:]))


def random_grid(rng: random.Random, rows: int, cols: int, density: float) -> list[str]:
    return ["".join("#" if rng.random() < density else "." for _ in range(cols)) for _ in range(rows)]


GRID = [
    ".....",
    ".###.",
    "...#.",
    "#.#..",
    ".....",
]


def test_example() -> None:
    s, t = (2, 0), (2, 4)
    path = hadlock_algorithm(GRID, s, t)
    assert path is not None and is_path(GRID, path, s, t)
    det, _, _ = hadlock_search(GRID, s, t)
    assert det[t] == 2
    assert len(path) - 1 == manhattan(s, t) + 2 * det[t] == 8


def test_edges() -> None:
    assert hadlock_algorithm(["."], (0, 0), (0, 0)) == [(0, 0)]
    assert hadlock_algorithm([".#."], (0, 0), (0, 2)) is None
    assert hadlock_algorithm([".", "#"], (0, 0), (1, 0)) is None
    assert hadlock_algorithm(["...", "...", "..."], (0, 0), (2, 2)) is not None


def test_against_bfs(seed: int = 11) -> None:
    rng = random.Random(seed)
    for _ in range(400):
        rows, cols = rng.randint(1, 9), rng.randint(1, 9)
        grid = random_grid(rng, rows, cols, rng.choice([0.1, 0.25, 0.4]))
        s = (rng.randrange(rows), rng.randrange(cols))
        t = (rng.randrange(rows), rng.randrange(cols))
        path = hadlock_algorithm(grid, s, t)
        if grid[s[0]][s[1]] == "#" or grid[t[0]][t[1]] == "#":
            assert path is None
            continue
        dist = bfs_dist(grid, s)
        if t not in dist:
            assert path is None
        else:
            assert path is not None and is_path(grid, path, s, t)
            assert len(path) - 1 == dist[t]
            det, _, _ = hadlock_search(grid, s, t)
            assert dist[t] == manhattan(s, t) + 2 * det[t]

History

F. O. Hadlock published the algorithm in 1977 in the journal Networks, under the title "A shortest path algorithm for grid graphs". He observed that on a grid the length of a path equals the Manhattan distance plus twice the number of steps away from the target, so the search can be ordered by this number instead of by distance. The same order follows from the A* search of Hart, Nilsson and Raphael (1968) with the Manhattan distance as the heuristic. Together with Lee's wave, Soukup's search (1978) and the line-probe routers, it became a standard maze router in textbooks of physical design.

References

  1. F. O. Hadlock, A shortest path algorithm for grid graphs, Networks 7(4), 323 to 334, 1977, the detour number, the identity of path length with the Manhattan distance plus twice the detours, and the search in order of detour number
  2. C. Y. Lee, An algorithm for path connections and its applications, IRE Transactions on Electronic Computers EC-10(3), 346 to 365, 1961, the wave expansion and backtrace that Hadlock's search replaces
  3. P. E. Hart, N. J. Nilsson and B. Raphael, A formal basis for the heuristic determination of minimum cost paths, IEEE Transactions on Systems Science and Cybernetics 4(2), 100 to 107, 1968, the A* search, of which Hadlock's search is the case of unit steps and the Manhattan heuristic
  4. Naveed A. Sherwani, Algorithms for VLSI Physical Design Automation, 3rd edition, Kluwer, 1999, the section on Hadlock's algorithm in the chapter on maze routing (general locator)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example