Algorithm Search⌘K

Algorithmcore

Line-probe routing

Also called Hightower algorithm, Mikami-Tabuchi algorithm.

Routers that grow free horizontal and vertical line segments from both pins until two segments meet. Mikami-Tabuchi always finds a path if one exists; Hightower's faster form may not.

Time
Θ(M N) worst
Space
Θ(M N) extra
Where
M = the number of rows of the routing grid; N = the number of columns
Properties
deterministicnot exactiterative
Origin
K. Mikami, K. Tabuchi, D. W. Hightower, 1968

Line-probe routing is a family of routers for electronic design automation (EDA) that connect two pins with horizontal and vertical wires by growing whole free line segments instead of single grid cells. From each pin, a probe runs left and right, and up and down, until it hits an obstacle. Points on these lines start new probes at a right angle, level by level, until a line from the source meets a line from the target. In the version of Mikami and Tabuchi (1968) every point of a line is a new base point, so a path is always found if one exists. In Hightower's version (1969) only a few escape points start new lines, which is much faster but can miss a path. Neither version promises a shortest path.

In plain words

Lee's router floods the board square by square. A line-probe router looks along straight lines instead, like a person who stands at a pin and looks as far as possible up, down, left and right.

Do this from both pins. If a line seen from one pin crosses a line seen from the other, you have a wire with a few bends: go along the first line, turn at the crossing, and go along the second.

If the lines do not cross, walk along each line and look again at a right angle from every point on it. Each round adds one more bend. Keep going until two lines cross. If no new lines appear, there is no wire at all.

The wire found has few bends, but it can be longer than the shortest one.

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 path from ss to tt, or the answer that no path exists. Line-probe routers were made for printed circuit boards and for layouts with large obstacles, where a path with few bends and little memory matters more than the exact length. A shortest path is the task of Lee's algorithm.

A probe from a free cell bb in orientation oo, horizontal or vertical, gives the maximal run of free cells in the row or column of bb that contains bb. The cell bb is its base point.

The algorithm

This is the version of Mikami and Tabuchi, run from both ends.

  1. MIKAMI-TABUCHI(grid, s, t)
  2. 1for side X in {S, T}: mark the origin (s or t) as covered by X; todo_X ← [(origin, horizontal), (origin, vertical)]
  3. 2while todo_S or todo_T is not empty do
  4. 3for side X in {S, T} do
  5. 4next_X ← []
  6. 5for each (b, o) in todo_X do
  7. 6if X already has a line in orientation o through b then skip it
  8. 7for each cell c on the probe from b in orientation o do
  9. 8if c is not yet covered by X then
  10. 9record base_X(c) ← b
  11. 10if c is covered by the other side then return the path through c
  12. 11add (c, the other orientation) to next_X
  13. 12todo_X ← next_X
  14. 13return "no path"

The lines drawn in the ii-th round of line L2 are the lines of level ii. A cell first reached at level ii from ss is joined to ss by a path with at most ii bends: follow its line back to the base point, then the line of that base point, and so on. On line L10 the path goes from ss to cc by the base points of side SS, and from cc to tt by those of side TT. If this walk passes a cell twice, the loop between the two visits is cut out.

Example

Take a grid of 5 rows and 6 columns, rows and columns numbered from 0, with s=(2,0)s = (2, 0) and t=(2,5)t = (2, 5).

. . . . . .
. # # # # .
s . . . # t
# # # . # .
. . . . . .

At level 0, four lines are drawn.

level side base point orientation cells
0 S (2,0) horizontal (2,0) to (2,3)
0 S (2,0) vertical (0,0) to (2,0)
0 T (2,5) horizontal (2,5) only
0 T (2,5) vertical (0,5) to (4,5)
1 S (2,1) vertical (2,1) only
1 S (2,2) vertical (2,2) only
1 S (2,3) vertical (2,3) to (4,3)
1 S (0,0) horizontal (0,0) to (0,5): meets T at (0,5)

No line of level 0 from ss meets a line from tt. At level 1 the new cells of each line become base points in the other orientation. The vertical lines from (2,1)(2, 1) and (2,2)(2, 2) are blocked at once. The vertical line from (2,3)(2, 3) reaches the bottom row. The horizontal line from (0,0)(0, 0) runs along the top row and reaches (0,5)(0, 5), which lies on the vertical line from tt. The path goes up from ss to (0,0)(0, 0), right to (0,5)(0, 5) and down to tt:

(2,0),(1,0),(0,0),(0,1),…,(0,5),(1,5),(2,5)(2,0), (1,0), (0,0), (0,1), \ldots, (0,5), (1,5), (2,5),

with 9 steps and 2 bends. Here this is also the length found by Lee's algorithm. The route through the bottom row also has 9 steps but 3 bends.

Correctness

The proof shows the following.

  • Valid path. Every cell with a base point is joined to its base point by free cells in one row or column, so following base points gives a path from ss, and the same from tt. Cutting loops keeps it a path.
  • Completeness of Mikami-Tabuchi. The cells covered by one side are closed under free neighbors when no new line appears: a free neighbor of a covered cell lies on the perpendicular line through that cell, which is drawn at the next level. So if no meeting happens, the side of ss has covered the whole component of ss, and tt is not in it.
  • Not shortest. On the grid with rows ..., ... and .#., from s=(2,2)s = (2, 2) to t=(2,0)t = (2, 0), the lines of level 1 go through the top row first, and the path found has 6 steps while 4 suffice.
  • Hightower may fail. Hightower's rules start new lines only from chosen escape points, so the covered cells need not be closed under free neighbors. The search can then stop without a path even when one exists, as the textbook accounts of the method point out.
Proof: The Mikami-Tabuchi line search returns a valid path, finds one whenever one exists, and runs in time linear in the grid, but its path need not be shortestfull

Let GG be the graph of free cells, with an edge between cells that share a side. A run is a maximal set of free cells that are consecutive in one row (a horizontal run) or in one column (a vertical run). Every free cell lies in exactly one horizontal run and one vertical run. The probe from bb in orientation oo returns the run of orientation oo that contains bb. Fix one side XX, with origin xx (that is, ss or tt), and say that a cell is covered by XX when it has a base point baseX\mathrm{base}_X.

Lemma 1 (lines are drawn once). Side XX draws each run at most once.

Proof. When XX draws the run RR of orientation oo from a base bb, every cell of RR is marked as having a line of orientation oo from XX. Any later pair (b′,o)(b', o) with b′∈Rb' \in R is skipped by line L6, and a pair (b′,o)(b', o) with b′∉Rb' \notin R gives a different run. □\square

Lemma 2 (base chains). For every cell cc covered by XX, following baseX\mathrm{base}_X from cc reaches xx, and the cells passed between cc and its base point, and so on, form a walk from cc to xx in GG.

Proof. The origin has itself as base. Any other covered cell cc got baseX(c)=b\mathrm{base}_X(c) = b on line L9 from a run that contains both cc and bb, so the cells of the run between them are free and form a straight walk. The base bb was covered before cc. So following bases goes strictly back in the order of covering and ends at xx. □\square

Theorem 1 (valid path). When line L10 finds a cell cc covered by both sides, the walk from ss to cc by the bases of side SS, followed by the walk from cc to tt by the bases of side TT, is a walk from ss to tt in GG. Cutting out the part between two visits of the same cell, as long as a cell repeats, leaves a simple path from ss to tt.

Proof. By Lemma 2 for each side. Cutting a closed part of a walk keeps a walk with the same ends, and each cut makes it shorter, so the process stops with a walk in which no cell repeats. □\square

Lemma 3 (closure). Suppose the loop of line L2 ends with no meeting. Then the set KXK_X of cells covered by XX is the connected component of xx in GG.

Proof. Every covered cell is joined to xx by Lemma 2, so KXK_X lies in the component of xx. For the other direction, let c∈KXc \in K_X and let dd be a free neighbor of cc. The cells cc and dd lie in one run RR, of orientation oo say. Consider the moment cc was covered. If c=xc = x, the pair (x,o)(x, o) was in the first list. Otherwise cc was covered by a line of the other orientation o′o' through it, and line L11 added (c,o)(c, o) to the next list, since the orientation added is the other one of the line. Either way the pair (c,o)(c, o) is handled in a later round, unless the loop stops first, which it does not, because a list only becomes empty after all its pairs are handled. When it is handled, either XX draws the run RR now, or line L6 skips it because XX has already drawn a line of orientation oo through cc, which is RR. In both cases d∈Rd \in R is covered. So KXK_X is closed under free neighbors, and it contains xx, so it contains the whole component. □\square Theorem 2 (completeness). If tt is reachable from ss, the search stops on line L10 with a path. If tt is not reachable, it returns "no path".

Proof. Suppose tt is reachable and the loop ends with no meeting. By Lemma 3, side SS covers the component of ss, which contains tt. But tt is covered by side TT from the start, so the first time side SS covered tt, line L10 found a cell covered by both sides and stopped. This is a contradiction. If tt is not reachable, no cell is covered by both sides, since a common cell would join ss and tt by Lemma 2. The loop ends because by Lemma 1 each side draws finitely many lines, each pair is added at most once per newly covered cell, and the lists then become empty. □\square

Running time. By Lemma 1 each side draws each run at most once. The runs of one orientation partition the free cells, so the total length of all runs is at most 2MN2MN, and drawing a run takes time in proportion to its length. Each covered cell adds one pair to a list, so the lists have O(MN)O(MN) pairs in total, and each skipped pair costs O(1)O(1). The cutting of loops takes time in proportion to the length of the walk, which is O(MN)O(MN): each segment of a base chain lies in the run that covered its cell, these runs are distinct by Lemma 1, and their total length is at most 2MN2MN for each side. So the time is O(MN)O(MN), and the base points take O(MN)O(MN) space. □\square

Proposition (not exact). The path found need not be shortest.

Proof. Take the 3 by 3 grid with rows ..., ... and .#., s=(2,2)s = (2, 2) and t=(2,0)t = (2, 0). At level 0 the horizontal probe from ss is blocked at once, the vertical probe covers column 2, and side TT covers column 0 in the same way. At level 1 side SS first draws the horizontal line of (0,2)(0, 2), the top row. Its first cell, (0,0)(0, 0), is covered by side TT, so the search stops. The path goes up column 2, along the top row and down column 0, with 6 steps. The path (2,2),(1,2),(1,1),(1,0),(2,0)(2,2), (1,2), (1,1), (1,0), (2,0) has 4 steps. □\square

Complexity

  • Time. A side draws at most one line through each cell in each orientation, by line L6, and a line through a cell is the same maximal run for every base point on it. So each side draws each maximal run at most once, and the total length of all maximal runs is at most 2MN2MN. The time is O(MN)O(MN), and a maze that the lines must cover cell by cell gives Θ(MN)\Theta(MN).
  • Space. This implementation keeps a base point for every covered cell, Θ(MN)\Theta(MN). Line-probe routers on a gridless layout store only the line segments and the obstacles, which is their main saving over Lee's router.
  • Hightower. With only a few escape points per line, the number of lines is small, and in the gridless form the time depends on the number of obstacles rather than on the size of a grid.

Properties

  • What is proved. Mikami-Tabuchi finds a path whenever one exists. Hightower's version can fail on a grid where a path exists. Neither version promises a shortest path. A cell met at level ii from one side has a path to that side with at most ii bends.
  • What is measured. On 16362 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(47)), the path of the Mikami-Tabuchi implementation here was longer than the shortest in 347 grids, with a mean ratio of 1.0101 and a worst ratio of 3.0. These are toy inputs, not benchmark results.
  • Deterministic. The result depends on the order in which lines and cells are taken. The implementation draws side SS before side TT in each level and takes the cells of a line from left to right or from top to bottom.

Variants and improvements

  • Hightower's escape points. From each line, a new line starts only at an escape point: the point of the line from which a perpendicular line can pass the end of the obstacle that blocks the line. This makes the search very fast on boards with few large obstacles, at the cost of completeness.
  • Gridless routing. The probes do not need a grid. They can run in the plane among rectilinear obstacles, with the lines found by searching the obstacle edges. This is the setting of Hightower's paper.
  • Fewest bends. A path with the least number of bends among rectilinear obstacles is a minimum-link path. Line probes are a heuristic form of that search.
  • Fallback. A router can run Hightower's search first and fall back to Mikami-Tabuchi or to Lee's algorithm for the nets it could not route.

When to use it

  • When memory for a label per grid cell is too much, or the layout is gridless, and a path with few bends is wanted.
  • On boards or chips with few large obstacles, where a few long lines cover most of the free space.

When the path must be shortest, use Lee's algorithm or Hadlock's algorithm. When every existing path must be found, do not use Hightower's form alone.

Pitfalls

  • Treating Hightower as complete. Hightower's search can stop with no path. A router that uses it alone must report such nets as unrouted and retry them with a complete search.
  • Claiming a shortest path. The level structure counts bends, not steps. The first meeting can be a long way round.
  • Drawing a line twice. Without the test of line L6, every cell of a long run starts the same line again, and the time grows by a factor of the run length.
  • Loops in the path. The walk back by base points from both sides can pass the same cell twice. Cut out the loop, or the path is not simple.

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.

line_probe_routing.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/line-probe-routing/. The authors are listed in prov/CEQKHV.jsonl.

from typing import Optional, Sequence

Cell = tuple[int, int]

H, V = 0, 1  # orientation of a probe line: horizontal (along a row) or vertical


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 probe_line(grid: Sequence[str], b: Cell, o: int) -> list[Cell]:
    """The cells of the longest free horizontal (o = H) or vertical (o = V) segment through b."""
    dr, dc = (0, 1) if o == H else (1, 0)
    lo = b
    while is_free(grid, (lo[0] - dr, lo[1] - dc)):
        lo = (lo[0] - dr, lo[1] - dc)
    cells = []
    cur = lo
    while is_free(grid, cur):
        cells.append(cur)
        cur = (cur[0] + dr, cur[1] + dc)
    return cells


def chain(base: dict[Cell, Cell], c: Cell) -> list[Cell]:
    """Cells from c back to the origin of its side, following each line to its base point."""
    out = [c]
    cur = c
    while base[cur] != cur:
        b = base[cur]
        dr = (b[0] > cur[0]) - (b[0] < cur[0])
        dc = (b[1] > cur[1]) - (b[1] < cur[1])
        while cur != b:
            cur = (cur[0] + dr, cur[1] + dc)
            out.append(cur)
    return out


def remove_loops(path: list[Cell]) -> list[Cell]:
    """Cut out every closed loop, so that no cell repeats."""
    out: list[Cell] = []
    pos: dict[Cell, int] = {}
    for c in path:
        if c in pos:
            k = pos[c]
            for d in out[k + 1:]:
                del pos[d]
            del out[k + 1:]
        else:
            pos[c] = len(out)
            out.append(c)
    return out


def line_probe_search(grid: Sequence[str], s: Cell, t: Cell) -> tuple[Optional[Cell], list[dict[Cell, Cell]], list[list[tuple[int, Cell, int]]]]:
    """Mikami-Tabuchi line probes from s and t, level by level.

    Returns the meeting cell (or None), the base point of each covered cell for
    each side, and for each level the lines drawn as (side, base point, orientation).
    """
    base: list[dict[Cell, Cell]] = [{s: s}, {t: t}]
    covered: list[list[set[Cell]]] = [[set(), set()], [set(), set()]]
    levels: list[list[tuple[int, Cell, int]]] = []
    if s == t:
        return s, base, levels
    todo: list[list[tuple[Cell, int]]] = [[(s, H), (s, V)], [(t, H), (t, V)]]  # @line L1
    while todo[0] or todo[1]:  # @line L2
        drawn: list[tuple[int, Cell, int]] = []
        new_todo: list[list[tuple[Cell, int]]] = [[], []]  # @line L4
        for side in (0, 1):  # @line L3
            for b, o in todo[side]:  # @line L5
                if b in covered[side][o]:  # @line L6
                    continue
                drawn.append((side, b, o))
                for c in probe_line(grid, b, o):  # @line L7
                    covered[side][o].add(c)
                    if c in base[side]:  # @line L8
                        continue
                    base[side][c] = b  # @line L9
                    if c in base[1 - side]:  # @line L10
                        levels.append(drawn)
                        return c, base, levels
                    new_todo[side].append((c, 1 - o))  # @line L11
        levels.append(drawn)
        todo = new_todo  # @line L12
    return None, base, levels  # @line L13


def line_probe_routing(grid: Sequence[str], s: Cell, t: Cell) -> Optional[list[Cell]]:
    """Return a path of cells from s to t found by Mikami-Tabuchi line probes, or None.

    grid is a list of equal-length strings, '#' marks a blocked cell. A path is
    found whenever one exists. It need not be shortest.
    """
    if not is_free(grid, s) or not is_free(grid, t):
        return None
    meet, base, _ = line_probe_search(grid, s, t)
    if meet is None:
        return None
    from_s = chain(base[0], meet)
    from_s.reverse()
    to_t = chain(base[1], meet)
    return remove_loops(from_s + to_t[1:])
test_line_probe_routing.py 89 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/line-probe-routing/. The authors are listed in prov/CEQKHV.jsonl.

import random

from line_probe_routing import H, V, line_probe_routing, line_probe_search, probe_line


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_simple_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 or len(set(path)) != len(path):
        return False
    if any(grid[r][c] != "." for r, c in path):
        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_probe_line() -> None:
    assert probe_line(GRID, (2, 1), H) == [(2, 0), (2, 1), (2, 2), (2, 3)]
    assert probe_line(GRID, (2, 3), V) == [(2, 3), (3, 3), (4, 3)]


def test_example() -> None:
    s, t = (2, 0), (2, 5)
    path = line_probe_routing(GRID, s, t)
    assert path is not None and is_simple_path(GRID, path, s, t)
    meet, _, levels = line_probe_search(GRID, s, t)
    assert meet is not None and len(levels) == 2


def test_not_shortest() -> None:
    grid = ["...", "...", ".#."]
    path = line_probe_routing(grid, (2, 2), (2, 0))
    assert path == [(2, 2), (1, 2), (0, 2), (0, 1), (0, 0), (1, 0), (2, 0)]
    assert bfs_dist(grid, (2, 2))[(2, 0)] == 4


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


def test_against_bfs(seed: int = 17) -> None:
    rng = random.Random(seed)
    for _ in range(500):
        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 = line_probe_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_simple_path(grid, path, s, t)
            assert len(path) - 1 >= dist[t]

History

K. Mikami and K. Tabuchi presented their line search at the IFIP Congress in 1968 for the routing of printed circuit conductors. D. W. Hightower presented his line-routing method at the 6th Design Automation Workshop in 1969. His method works in the continuous plane and uses escape points to keep the number of lines small. Both methods came after Lee's grid router of 1961 and use much less memory than a label for every cell. Later routers combined line probes with maze search, using the probes for long open runs and the grid search where the layout is crowded.

References

  1. K. Mikami and K. Tabuchi, A computer program for optimal routing of printed circuit conductors, Proceedings of the IFIP Congress 1968, volume 2, North-Holland, 1475 to 1478, the lines from the source and the target, the base points of each level and the meeting of the two trees of lines
  2. D. W. Hightower, A solution to line-routing problems on the continuous plane, Proceedings of the 6th Design Automation Workshop, 1 to 24, 1969, the escape lines and escape points in the continuous plane (general locator)
  3. C. Y. Lee, An algorithm for path connections and its applications, IRE Transactions on Electronic Computers EC-10(3), 346 to 365, 1961, the cell-by-cell wave that line probes replace by whole segments
  4. Naveed A. Sherwani, Algorithms for VLSI Physical Design Automation, 3rd edition, Kluwer, 1999, the section on line-probe algorithms 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.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