Algorithm Search⌘K

Algorithmcore

Soukup's algorithm

Also called Soukup fast maze router.

A maze router that goes depth first toward the target and falls back to a breadth-first wave when blocked. It finds a path if one exists, but not always a shortest one.

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
deterministicnot exactiterative
Origin
J. Soukup, 1978

Soukup's algorithm is a fast maze router for electronic design automation (EDA). Like Lee's algorithm, it connects two cells of a routing grid around blocked cells, but it first runs straight at the target, depth first, and uses a breadth-first wave only to get around obstacles. Each cell is reached once. The router always finds a path when one exists, and on open grids it reaches the target after visiting little more than the cells of the path. The price is that the path need not be shortest.

In plain words

Lee's router spreads out in all directions at once. That is safe, but slow when the goal is far away. Soukup's router walks straight at the goal and keeps going in the same direction as long as each step brings it nearer.

When the walk hits a wall, the router does not give up. It writes down all the squares next to the walk that go sideways or back, and it starts new walks from them. These new walks start one ring farther out, like the rings in Lee's router.

A square is never visited twice. So the router does a small amount of work and always finds a way when one exists. But the first walk that reaches the goal may have gone the wrong way around a wall, so the wire can be longer than needed.

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 some path from ss to tt, or the answer that no path exists. Unlike Lee's algorithm, Soukup's router does not promise a shortest path. For cells u,vu, v write md(u,v)\mathrm{md}(u, v) for the Manhattan distance of their coordinates. A neighbor vv of uu is toward tt if md(v,t)<md(u,t)\mathrm{md}(v, t) < \mathrm{md}(u, t).

The algorithm

  1. SOUKUP(grid, s, t)
  2. 1mark s as reached; wave ← [s]
  3. 2while wave is not empty do
  4. 3next ← []
  5. 4for each cell c of wave do
  6. 5stack ← [c]
  7. 6while stack is not empty do
  8. 7u ← pop stack
  9. 8for each free neighbor v of u that is not reached do
  10. 9mark v as reached; parent(v) ← u
  11. 10if v = t then return the path from s to t by the parent links
  12. 11if v is toward t then push v on stack (the neighbor in the direction of the last step last, so it is popped first)
  13. 12else add v to next
  14. 13wave ← next
  15. 14return "no path"

Lines L5 to L12 are the depth-first part: from a cell of the current wave, the search follows toward steps as far as it can, keeping its direction when possible. Line L12 is the breadth-first part: every neighbor that is not toward tt waits for the next wave. Textbook accounts describe the toward part as a run that keeps its direction until it reaches the target or an obstacle, and the fallback as Lee's expansion. This page gives the router in the form above, which keeps both parts and reaches each cell once.

Example

Take a grid of 5 rows and 2 columns, rows and columns numbered from 0, with one blocked cell at (1,0)(1, 0). Let s=(4,1)s = (4, 1) and t=(0,0)t = (0, 0), so md(s,t)=5\mathrm{md}(s, t) = 5.

t .
# .
. .
. .
. s

The neighbors are tried in the order up, right, down, left. The search runs like this.

step cell popped new neighbors toward tt next wave
1 (4,1) (3,1), (4,0) both
2 (4,0) (3,0) yes
3 (3,0) (2,0) yes
4 (2,0) (2,1) no, md\mathrm{md} grows from 2 to 3 (2,1)
5 (3,1) none
6 (2,1) (1,1) yes
7 (1,1) (0,1) yes
8 (0,1) (0,0) = tt stop

In step 1 both neighbors of ss are toward tt. They are pushed in the order found, so (4,0)(4, 0) is popped first. The run goes up the left column until the blocked cell (1,0)(1, 0) stops it. The only way on is the step right to (2,1)(2, 1), which is not toward tt, so it waits for the next wave. The cell (3,1)(3, 1) is then popped, but its only new neighbor would be (2,1)(2, 1), which is already reached. In the second wave, the run from (2,1)(2, 1) goes up the right column and left to tt. The path found is

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

with 7 steps. The shortest path, straight up the right column and then left, has 5 steps. The search reached (2,1)(2, 1) first from (2,0)(2, 0), and since each cell is reached only once, the shorter way through (3,1)(3, 1) was lost.

Correctness

The proof shows the following.

  • Each cell once. A cell is marked when it is first found and never again, so the parent links form a tree rooted at ss.
  • Every reached cell is expanded. A reached cell goes either on the stack, which is emptied before the wave ends, or into the next wave. So every reached cell is popped exactly once, unless the search stops at tt.
  • Completeness. If tt is reachable from ss, it is reached: the reached set is closed under free neighbors when the waves run out, so it is the whole component of ss.
  • Valid path. The parent links of tt lead back to ss through neighbors, so the router returns a path.
  • Not shortest. The example above has a path of 7 steps where 5 suffice.
Proof: Soukup's router reaches each cell once and finds a path whenever one exists, but the path need not be shortestfull

Let GG be the graph of free cells, with an edge between cells that share a side. Let CC be the set of cells reachable from ss in GG. Call a cell reached once line L1 or line L9 marks it.

Lemma 1 (each cell once). A cell is marked at most once, and it is put at most once on a stack or in a wave. The parent links form a tree on the reached cells, rooted at ss.

Proof. Line L8 only looks at cells that are not reached, and line L9 marks them at once. After that the cell is never chosen again by line L8. A cell enters a stack (line L11) or the next wave (line L12) only right after it is marked, so at most once. The parent of a cell is set once, to a cell that was reached before it, so following parents strictly goes back in the order of marking and ends at ss. □\square

Lemma 2 (every reached cell is popped). If the search does not stop on line L10, every reached cell is popped exactly once on line L7.

Proof. The source is popped, as the first cell of the first wave. Any other reached cell went either on a stack or into the list next. A stack is emptied by the loop of line L6 before the loop of line L4 moves on, so every cell pushed on it is popped. Every cell of next becomes a cell of the following wave on line L13 and is pushed on line L5 when its turn comes, and popped. The loop of line L2 only ends when a wave is empty, so no list next is left unprocessed. □\square

Lemma 3 (closure). If the search ends on line L14, the set of reached cells is CC.

Proof. Reached cells are in CC, since each is a neighbor of an earlier reached cell. For the other direction, let uu be reached and vv a free neighbor of uu. By Lemma 2, uu is popped, and at that time line L8 either marks vv or finds it already reached. So the reached set is closed under free neighbors and contains ss. Every cell of CC is joined to ss by a path, and induction along the path shows that it is reached. □\square

Theorem (completeness and validity). If t∈Ct \in C, the router returns a path from ss to tt. If t∉Ct \notin C, it returns "no path".

Proof. If t∈Ct \in C and the search reached line L14, Lemma 3 would say that tt is reached. But tt is checked on line L10 right when it is marked, so the search would have stopped there. So the search stops on line L10. By Lemma 1 the parent links of tt lead to ss, and each link joins neighbors, so they give a path. If t∉Ct \notin C, it is never marked, and since each cell is popped at most once the search ends, on line L14. □\square

Running time. By Lemma 1 and Lemma 2 each cell is pushed and popped at most once, and each pop looks at 4 neighbors. The sorting on line L11 handles at most 4 cells. So the time is O(MN)O(MN). The marks, parents, stack and waves take O(MN)O(MN) space. □\square

Proposition (not exact). There are grids where the path found is longer than the shortest path.

Proof. Take the 5 by 2 grid with the blocked cell (1,0)(1, 0), s=(4,1)s = (4, 1) and t=(0,0)t = (0, 0), with neighbors tried up, right, down, left. Both (3,1)(3, 1) and (4,0)(4, 0) are toward tt. The cell (4,0)(4, 0) is pushed last and popped first, and the run goes up to (2,0)(2, 0), which marks (2,1)(2, 1) with parent (2,0)(2, 0). When (3,1)(3, 1) is popped, (2,1)(2, 1) is already reached. So the path to tt goes through (4,0),(3,0),(2,0),(2,1),(1,1),(0,1)(4, 0), (3, 0), (2, 0), (2, 1), (1, 1), (0, 1) and has 7 steps, while the path (4,1),(3,1),(2,1),(1,1),(0,1),(0,0)(4,1), (3,1), (2,1), (1,1), (0,1), (0,0) has 5. □\square

Complexity

  • Time. Each cell is reached once and popped once, and each pop looks at 4 neighbors. So the time is O(MN)O(MN), and a maze that forces the search to visit every cell gives Θ(MN)\Theta(MN).
  • Space. The marks and parents take Θ(MN)\Theta(MN) memory. The stack and the waves hold each cell at most once.
  • Open grid. With no blockage, every step on a monotone path is toward tt, and the search walks straight to tt, visiting about md(s,t)\mathrm{md}(s, t) cells and their neighbors.

Properties

  • What is proved. The router finds a path whenever one exists, and it visits each cell at most once. It does not promise a shortest path, and no bound on the extra length is known for general grids. The extra length can be large: a wall that the toward run follows into a dead end makes the path go around it.
  • What is measured. On 16466 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(43)), the path was longer than the shortest in 87 grids, with a mean ratio of 1.0015 and a worst ratio of 1.4. The search visited fewer cells than Lee's wave labeled in 15346 grids. These are toy inputs, not benchmark results.
  • Deterministic. The result depends on the order of the neighbors and on the rule that keeps the direction of the last step.

Variants and improvements

  • Straight runs only. The toward part can be a straight run that never turns until it is blocked. The form on this page lets the depth-first part turn to another toward direction when the first one is blocked.
  • Keep the direction. Preferring the neighbor in the direction of the last step gives paths with few bends, which matter for vias in two-layer routing.
  • Hadlock's order. If a shortest path is needed, order the cells by detour number as in Hadlock's algorithm. This costs a little more work but restores the guarantee.
  • Line probes. Line-probe routing works with whole free segments instead of cells, and it trades the shortest path for less memory as well.

When to use it

  • To route many short connections quickly on a grid that is mostly open, where a short path is good enough.
  • As a first try in a router, with Lee's or Hadlock's search kept for the nets where the path is too long.

When the length of each net matters, use Lee's algorithm or Hadlock's algorithm, which find shortest paths.

Pitfalls

  • Claiming a shortest path. The router is complete but not exact. Do not use its length as the distance between the pins.
  • Marking too late. A cell must be marked when it is first found, on line L9, not when it is popped. Otherwise a cell can be put on the stack or in a wave many times, and the time bound is lost.
  • Forgetting the waves. A depth-first run toward the target alone gets stuck behind a wall. The cells that are not toward the target must be kept for the next wave, or the router can fail on a grid that has a path.
  • Stopping at a label. The search stops when it finds tt on line L10. There is no backtrace by labels, as in Lee's router, so the parent links must be kept.

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.

soukup_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/soukup-algorithm/. The authors are listed in prov/34KRY7.jsonl.

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 soukup_search(grid: Sequence[str], s: Cell, t: Cell) -> tuple[dict[Cell, Cell], list[Cell]]:
    """Soukup's search. Returns the parent of each reached cell and the expansion order.

    From each cell of the current wave, the search goes depth-first through
    neighbors that are closer to t. A neighbor that is not closer to t goes to
    the next wave, as in a breadth-first search. Each cell is reached once.
    The search stops as soon as t is reached.
    """
    parent: dict[Cell, Cell] = {s: s}
    order: list[Cell] = []
    wave = [s]  # @line L1
    if s == t:
        return parent, [s]
    while wave:  # @line L2
        nxt: list[Cell] = []  # @line L3
        for c in wave:  # @line L4
            stack = [(c, None)]  # @line L5
            while stack:  # @line L6
                u, came = stack.pop()  # @line L7
                order.append(u)
                toward: list[tuple[Cell, tuple[int, int]]] = []
                for d in STEPS:  # @line L8
                    v = (u[0] + d[0], u[1] + d[1])
                    if not is_free(grid, v) or v in parent:
                        continue
                    parent[v] = u  # @line L9
                    if v == t:  # @line L10
                        order.append(v)
                        return parent, order
                    if manhattan(v, t) < manhattan(u, t):  # @line L11
                        toward.append((v, d))
                    else:
                        nxt.append(v)  # @line L12
                # Push so that a step in the same direction as the last one is popped first.
                toward.sort(key=lambda vd: vd[1] == came)
                for v, d in toward:
                    stack.append((v, d))
        wave = nxt  # @line L13
    return parent, order  # @line L14


def soukup_algorithm(grid: Sequence[str], s: Cell, t: Cell) -> Optional[list[Cell]]:
    """Return a path of cells from s to t found by Soukup's router, or None.

    grid is a list of equal-length strings, '#' marks a blocked cell. The path
    lists s first and t last. It exists whenever some path exists, but it need
    not be shortest.
    """
    if not is_free(grid, s) or not is_free(grid, t):
        return None
    parent, _ = soukup_search(grid, s, t)
    if t not in parent:
        return None
    path = [t]
    while path[-1] != s:
        path.append(parent[path[-1]])
    path.reverse()
    return path
test_soukup_algorithm.py 83 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/soukup-algorithm/. The authors are listed in prov/34KRY7.jsonl.

import random

from soukup_algorithm import manhattan, soukup_algorithm, soukup_search


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
    if len(set(path)) != len(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)]


TRAP = [
    "..",
    "#.",
    "..",
    "..",
    "..",
]


def test_not_shortest() -> None:
    s, t = (4, 1), (0, 0)
    path = soukup_algorithm(TRAP, s, t)
    assert path == [(4, 1), (4, 0), (3, 0), (2, 0), (2, 1), (1, 1), (0, 1), (0, 0)]
    assert is_path(TRAP, path, s, t)
    assert len(path) - 1 == 7 and bfs_dist(TRAP, s)[t] == 5


def test_edges() -> None:
    assert soukup_algorithm(["."], (0, 0), (0, 0)) == [(0, 0)]
    assert soukup_algorithm([".#."], (0, 0), (0, 2)) is None
    assert soukup_algorithm(["..."], (0, 0), (0, 2)) == [(0, 0), (0, 1), (0, 2)]
    parent, order = soukup_search(["....."], (0, 0), (0, 4))
    assert order == [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4)]


def test_against_bfs(seed: int = 13) -> None:
    rng = random.Random(seed)
    longer = 0
    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 = soukup_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]
            longer += len(path) - 1 > dist[t]
    assert longer > 0

History

J. Soukup presented the "fast maze router" at the 15th Design Automation Conference in 1978. Lee's router (1961) was reliable but slow on large printed circuit boards, and Hadlock (1977) had sped it up while keeping shortest paths. Soukup gave up the shortest path and ran straight toward the target, using Lee's wave only when the direct run was blocked. The idea of a fast directed search with a breadth-first fallback appears in many later grid routers.

References

  1. J. Soukup, Fast maze router, Proceedings of the 15th Design Automation Conference, 100 to 102, 1978, the search that runs toward the target until it is blocked and then expands a breadth-first wave (general locator)
  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 breadth-first wave that Soukup's router uses when the direct run is blocked
  3. Naveed A. Sherwani, Algorithms for VLSI Physical Design Automation, 3rd edition, Kluwer, 1999, the section on Soukup'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