Algorithm Search⌘K

Algorithmintro

Lee's maze routing algorithm

Also called Lee algorithm, wave propagation routing.

Lee's router expands a wave of grid cells from the source by breadth-first search until it reaches the target, then traces back a shortest path.

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
C. Y. Lee, 1961

Lee's algorithm is a maze router for electronic design automation (EDA): it connects two cells of a routing grid by a path that avoids blocked cells and has the fewest steps. It is a breadth-first search on the grid graph. A wave of labels grows out from the source, one step at a time, until it reaches the target. A backtrace then walks from the target to the source through labels that fall by 1 at each step. If a path exists, the algorithm finds a shortest one, at the cost of Θ(MN)\Theta(MN) time and memory on an M×NM \times N grid.

In plain words

Think of the chip as a sheet of squared paper. Some squares are full, and a wire cannot cross them. You want to join two squares with a wire that is as short as possible.

Write 0 in the start square. Write 1 in each free square next to it. Then write 2 in each free empty square next to a 1, and so on, like a ring of water that spreads out from a stone dropped in a pond. Stop when the ring reaches the goal square.

The number in the goal square is the length of the shortest wire. To draw the wire, start at the goal and step to a neighbor with a number one smaller. Keep doing this until you reach 0. If the ring stops growing before it reaches the goal, no wire is possible.

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. Two cells are neighbors if they share a side. A path is a sequence of free cells in which each cell is a neighbor of the next. Its length is the number of steps. The output is a shortest path from ss to tt, or the answer that no path exists. In a detailed router the blocked cells are the pins, the wires of nets that are already routed and the obstacles. In a global router the cells are larger tiles, and the same search runs with costs on the edges (see global routing).

The algorithm

  1. LEE(grid, s, t)
  2. 1label(s) ← 0; queue ← [s]
  3. 2while queue is not empty and t has no label do
  4. 3u ← remove the first cell of queue
  5. 4for each free neighbor v of u with no label do
  6. 5label(v) ← label(u) + 1; add v at the end of queue
  7. 6if t has no label then return "no path"
  8. 7path ← [t]; u ← t
  9. 8while u ≠ s do
  10. 9u ← a neighbor of u with label(u) - 1 (fixed order: up, right, down, left)
  11. 10add u to path
  12. 11return path in reverse order

Lines L1 to L5 are the wave expansion. All cells with label kk form the kk-th wave front. Lines L7 to L10 are the backtrace. The fixed order of neighbors on line L9 decides which shortest path is returned when there are several.

Example

Take this grid of 5 rows and 5 columns, with rows and columns numbered from 0, s=(2,0)s = (2, 0) and t=(2,4)t = (2, 4). A # is a blocked cell. The second grid shows the label of each cell after the expansion.

. . . . .        2 3 4 5 6
. # # # .        1 # # # 7
s . . # t        0 1 2 # 8
# . # . .        # 2 # 6 7
. . . . .        4 3 4 5 6

The wave fronts are:

label cells
0 (2,0)
1 (1,0), (2,1)
2 (0,0), (2,2), (3,1)
3 (0,1), (4,1)
4 (0,2), (4,0), (4,2)
5 (0,3), (4,3)
6 (0,4), (3,3), (4,4)
7 (1,4), (3,4)
8 (2,4)

The target gets label 8, so the shortest path has 8 steps. All 19 free cells were labeled before the target. The backtrace starts at (2,4)(2, 4) with label 8. The neighbor above, (1,4)(1, 4), has label 7, so it goes there, then to (0,4)(0, 4) with 6, and along the top row to (0,0)(0, 0) with 2, then down to (1,0)(1, 0) and (2,0)(2, 0). 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).

The route along the bottom, through (3,4)(3, 4), also has 8 steps. The backtrace takes the top route because it tries the neighbor above first.

Correctness

The proof shows the following.

  • Labels are distances. Each label is the length of a shortest path from ss to that cell, as in breadth-first search, because the queue holds the cells in order of their labels.
  • Early stop is safe. When tt gets its label LL, every cell at distance less than LL already has its label. So line L9 always finds a neighbor with the label one less.
  • Shortest path. The backtrace makes LL steps and every step goes to a neighbor, so the path has length LL, the distance from ss to tt.
  • No false failures. If the queue empties before tt is labeled, the labeled cells form the whole component of ss, so no path exists.
  • Akers coding. Two bits per cell are enough for the backtrace, because the two kinds of neighbors of a cell, one step nearer to ss or one step farther, always get different bits in the sequence 0, 0, 1, 1.
Proof: Lee's algorithm labels cells with their distance from the source and backtraces a shortest path, and two bits per cell are enoughfull

Let GG be the graph whose vertices are the free cells of the grid, with an edge between two cells that share a side. Let δ(v)\delta(v) be the number of steps of a shortest path from ss to vv in GG, or ∞\infty if there is none. Write L=δ(t)L = \delta(t).

Lemma 1 (queue order). At every moment the labels of the cells in the queue, from first to last, are non-decreasing, and the last label is at most the first label plus 1.

Proof. At the start the queue holds only ss. Line L3 removes the first cell uu, with the smallest label kk, so the remaining labels lie in {k,k+1}\{k, k+1\}. Line L5 adds cells with label k+1k + 1 at the end. Both properties hold again. □\square

By Lemma 1 the cells leave the queue in order of their labels. Call phase kk the part of the run in which the cells with label kk are removed and processed. A label k+1k + 1 is only set in phase kk.

Lemma 2 (labels are distances). For each k≥0k \ge 0, at the start of phase kk the cells with a label at most kk are exactly the cells with δ(v)≤k\delta(v) \le k, and each of them has label(v)=δ(v)\mathrm{label}(v) = \delta(v). No cell has a label larger than kk.

Proof. By induction on kk. At the start of phase 0 only ss has a label, 0, and δ(s)=0\delta(s) = 0 while δ(v)≥1\delta(v) \ge 1 for every other cell.

Assume the claim at the start of phase kk, and let phase kk run to its end. The cells labeled in phase kk get label k+1k + 1, and they are the unlabeled free neighbors of cells with label kk. Such a cell vv is next to a cell with δ=k\delta = k, so δ(v)≤k+1\delta(v) \le k + 1. It had no label, so by the assumption δ(v)>k\delta(v) > k. So δ(v)=k+1=label(v)\delta(v) = k + 1 = \mathrm{label}(v). Conversely, let δ(v)=k+1\delta(v) = k + 1, and let ww be the cell before vv on a shortest path, with δ(w)=k\delta(w) = k. By the assumption ww has label kk, so it is processed in phase kk. At that moment vv has no label of at most kk, so line L4 labels it now, or it was labeled earlier in the same phase with k+1k + 1. No cell gets label k+2k + 2 in phase kk. This is the claim for k+1k + 1. □\square

Lemma 3 (early stop). When the loop of lines L2 to L5 stops because tt is labeled, label(t)=L\mathrm{label}(t) = L and every cell vv with δ(v)<L\delta(v) < L has label(v)=δ(v)\mathrm{label}(v) = \delta(v).

Proof. The label of tt is set in some phase kk, and it is k+1k + 1. By Lemma 2 applied at the start of phase kk and in its proof, label(t)=δ(t)=L\mathrm{label}(t) = \delta(t) = L, so k=L−1k = L - 1. At the start of phase L−1L - 1, Lemma 2 says that every cell with δ(v)≤L−1\delta(v) \le L - 1 has its correct label. □\square

Lemma 4 (backtrace). If tt is labeled, lines L7 to L10 stop after exactly LL steps, and the cells form a path from tt to ss in GG.

Proof. Let u≠su \ne s be the current cell with δ(u)=k≥1\delta(u) = k \ge 1. A shortest path from ss to uu has a cell ww before uu with δ(w)=k−1<L\delta(w) = k - 1 < L. By Lemma 3, ww is labeled, and by Lemma 2 its label is k−1k - 1. So line L9 finds a neighbor with label k−1k - 1, and the label falls by exactly 1 at each step. After LL steps the label is 0, and the only cell with δ=0\delta = 0 is ss. Every step goes between neighbors, so the cells form a path. □\square

Theorem (correctness and completeness). If tt is reachable from ss, the algorithm returns a path of length δ(t)\delta(t), which is a shortest path. Otherwise it returns "no path".

Proof. If tt is reachable, the queue cannot become empty before tt is labeled. Indeed, by Lemma 2 there is a cell with label kk for every k≤δ(t)k \le \delta(t), since a shortest path to tt has a cell at each distance, and phase δ(t)−1\delta(t) - 1 labels tt. Lemma 4 then gives a path of length L=δ(t)L = \delta(t). If tt is not reachable, no label is ever given to tt, since labels follow edges from ss, so line L6 reports that there is no path. □\square

Running time. Each free cell gets a label at most once, so it enters and leaves the queue at most once. Each removal looks at 4 neighbors. The expansion takes O(MN)O(MN) time. Each backtrace step looks at 4 neighbors, and there are L≤MNL \le MN steps. The labels take one entry per cell, Θ(MN)\Theta(MN) space. □\square

Lemma 5 (Akers coding). Replace label(v)\mathrm{label}(v) by a(v)=σ(label(v) mod 4)a(v) = \sigma(\mathrm{label}(v) \bmod 4), where σ=(0,0,1,1)\sigma = (0, 0, 1, 1). If the backtrace knows the label kk of the current cell modulo 4, the neighbor it needs is the unique kind of labeled neighbor with a=σ((k−1) mod 4)a = \sigma((k - 1) \bmod 4).

Proof. The grid graph is bipartite: a step changes the parity of row plus column. So two neighbors have labels of different parity, and since both labels are distances, they differ by exactly 1. A labeled neighbor of a cell with label kk has label k−1k - 1 or k+1k + 1. These two numbers differ by 2, and σ(j)≠σ(j+2 mod 4)\sigma(j) \ne \sigma(j + 2 \bmod 4) for each jj, because σ\sigma is 0 on {0,1}\{0, 1\} and 1 on {2,3}\{2, 3\}. So the bit tells the two kinds apart. The backtrace starts at tt, whose label is known from the step count of the expansion, and lowers kk by 1 at each step. A cell then needs two bits: one for the states "free and unlabeled" or "blocked" and one for a(v)a(v), or a code of four states in two bits. □\square

Complexity

  • Time. Each free cell enters the queue at most once, and each cell has at most 4 neighbors. So the expansion takes O(MN)O(MN) time, and the backtrace takes O(L)=O(MN)O(L) = O(MN). In the worst case, for example when tt is the last free cell of a long spiral, the wave visits every cell, so the bound is Θ(MN)\Theta(MN).
  • Space. A label for every cell takes Θ(MN)\Theta(MN) memory. Lee stored the distance in each cell. With Akers' coding the label takes one bit, and with the free and blocked states a cell needs two bits.
  • Wasted work. The wave grows in all directions, also away from the target. In an open grid it labels about 2L22L^2 cells to find a path of length LL. Hadlock's algorithm and A* search aim the search at the target.

Properties

  • What is proved. If a path exists, Lee's algorithm finds a shortest one. If no path exists, it says so. These are the guarantees of breadth-first search.
  • Exact and deterministic. The result depends only on the grid and on the fixed order of neighbors in the backtrace.
  • One net at a time. The path is shortest for this net, given the wires that are already in place. The order in which nets are routed changes the result, and a net routed early can block a later one. Lee's algorithm says nothing about the total wire length of many nets.
  • Uniform cost. Every step costs 1. Bends and vias have no cost unless the search is changed, as in the variants below.

Variants and improvements

  • Akers coding (1967). Label the cells with the sequence 0, 0, 1, 1, 0, 0, 1, 1, ... by distance, instead of the distance itself. A cell then needs two bits, and the backtrace still works.
  • Bidirectional search. Grow waves from ss and from tt and stop when they meet. In an open grid this labels about half as many cells.
  • Bounding box. Search only inside a box around ss and tt with a margin. This is faster, but it can miss a path that leaves the box.
  • Costs on cells and edges. With costs for bends, vias, layers or congestion, the wave becomes Dijkstra's algorithm with a priority queue. With costs 0 and 1 it is a 0-1 BFS. Global routers and negotiated congestion routing use this form.
  • Search toward the target. Hadlock's algorithm orders the cells by detour number, which is A* search with the Manhattan distance. Soukup's algorithm runs depth first toward the target and gives up the guarantee of a shortest path.
  • Multi-pin nets. Start the wave from all cells of the tree built so far, and connect the nearest unconnected pin. Repeat until all pins are connected. This builds a Steiner tree heuristically.
  • Line probes. Line-probe routing works with whole free segments instead of single cells and needs much less memory.

When to use it

  • To route a two-pin connection on a grid when a shortest path is needed and a path must be found whenever one exists.
  • As the base search of a rip-up and reroute loop, with costs added.
  • On small grids or inside a small window, where Θ(MN)\Theta(MN) memory is not a problem.

When the grid is large and open, use Hadlock's algorithm or A*, which label far fewer cells. When memory is the limit, use line-probe routing.

Pitfalls

  • Stopping too late. The expansion can stop as soon as tt has a label. Going on to fill the whole grid gives the same path but costs more time.
  • Backtrace without a fixed order. Any neighbor with the label one less is correct, but an order that is not fixed makes the result change from run to run. Some routers prefer the neighbor in the same direction as the last step, which gives fewer bends.
  • Diagonal moves. The grid has four neighbors per cell. Adding diagonal steps changes the problem, and the labels are no longer the rectilinear length.
  • Pins on blocked cells. If ss or tt is itself marked as blocked, for example because it is a pin of the net, the search must treat it as free.
  • Akers labels without the phase. With Akers' coding, the backtrace must know which bit it expects next. It starts from the bit of the target and steps back one position in the sequence at each cell.

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.

lee_maze_routing.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lee-maze-routing/. The authors are listed in prov/EQ37HH.jsonl.

from collections import deque
from typing import Optional, Sequence

Cell = tuple[int, int]

# Neighbor order: up, right, down, left. The backtrace uses the same order.
STEPS = ((-1, 0), (0, 1), (1, 0), (0, -1))


def free_neighbors(grid: Sequence[str], cell: Cell) -> list[Cell]:
    """Free cells next to cell, in the fixed order up, right, down, left."""
    r, c = cell
    out = []
    for dr, dc in STEPS:
        nr, nc = r + dr, c + dc
        if 0 <= nr < len(grid) and 0 <= nc < len(grid[nr]) and grid[nr][nc] != "#":
            out.append((nr, nc))
    return out


def lee_wave(grid: Sequence[str], s: Cell, t: Cell) -> dict[Cell, int]:
    """Wave expansion: label each cell with its distance from s, until t is labeled."""
    label = {s: 0}
    wave = deque([s])  # @line L1
    while wave and t not in label:  # @line L2
        u = wave.popleft()  # @line L3
        for v in free_neighbors(grid, u):  # @line L4
            if v not in label:
                label[v] = label[u] + 1  # @line L5
                wave.append(v)
    return label


def lee_maze_routing(grid: Sequence[str], s: Cell, t: Cell) -> Optional[list[Cell]]:
    """Return a shortest path of cells from s to t on the grid, or None.

    grid is a list of equal-length strings, '#' marks a blocked cell. Moves go
    to the four neighbors. The path lists s first and t last.
    """
    for r, c in (s, t):
        if not (0 <= r < len(grid) and 0 <= c < len(grid[r])) or grid[r][c] == "#":
            return None
    label = lee_wave(grid, s, t)
    if t not in label:  # @line L6
        return None
    path = [t]  # @line L7
    while path[-1] != s:  # @line L8
        u = path[-1]
        for v in free_neighbors(grid, u):  # @line L9
            if label.get(v) == label[u] - 1:
                path.append(v)  # @line L10
                break
    path.reverse()
    return path  # @line L11
test_lee_maze_routing.py 78 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lee-maze-routing/. The authors are listed in prov/EQ37HH.jsonl.

import random

from lee_maze_routing import lee_maze_routing, lee_wave


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
    for r, c in path:
        if grid[r][c] != ".":
            return False
    return all(abs(a[0] - b[0]) + abs(a[1] - b[1]) == 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:
    path = lee_maze_routing(GRID, (2, 0), (2, 4))
    assert path is not None and len(path) - 1 == 8
    assert is_path(GRID, path, (2, 0), (2, 4))
    label = lee_wave(GRID, (2, 0), (2, 4))
    assert label[(2, 4)] == 8


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


def test_against_bfs(seed: int = 7) -> 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 = lee_maze_routing(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]

History

C. Y. Lee, at Bell Telephone Laboratories, published the algorithm in 1961 for path connections on a grid, with wiring of printed circuit boards as the main use. E. F. Moore had described the same breadth-first labeling in 1959 to find the shortest path through a maze, and the method is the breadth-first search of graph theory. In 1967 S. B. Akers showed that the labels can be cut to two bits per cell with the sequence 0, 0, 1, 1. Lee's router became the base of grid routers in EDA. Later work aimed the search at the target, with Hadlock in 1977 and Soukup in 1978, or replaced the cells by line segments, with Mikami and Tabuchi in 1968 and Hightower in 1969.

References

  1. 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 from the source, the labels by distance and the backtrace from the target
  2. E. F. Moore, The shortest path through a maze, Proceedings of the International Symposium on the Theory of Switching, Part II, Harvard University Press, 285 to 292, 1959, the breadth-first labeling of a maze by distance from the start (general locator, not checked against the text)
  3. S. B. Akers, A modification of Lee's path connection algorithm, IEEE Transactions on Electronic Computers EC-16, 97 to 98, 1967, the labeling of cells with the repeating sequence 0, 0, 1, 1, which needs two bits per cell
  4. Naveed A. Sherwani, Algorithms for VLSI Physical Design Automation, 3rd edition, Kluwer, 1999, the chapter on maze routing (general locator)

Where this leads

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