Algorithmcore
Rectilinear minimum spanning tree
Also called RMST, L1 minimum spanning tree.
Builds the minimum spanning tree of points under the L1 metric in O(n log n) time, from a sparse graph that joins each point to a nearest point in each octant.
- Time
- Θ(n log n) worst
- Space
- Θ(n) extra
- Where
- n = the number of points
- Model
- Real RAM
- Properties
- deterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- F. K. Hwang, Andrew Chi Chih Yao, Hai Zhou, Narendra Shenoy, William Nicholls, 1979
The rectilinear minimum spanning tree (RMST) of a set of points in the plane is a minimum spanning tree of the complete graph on the points, where an edge costs the L1 distance . In electronic design automation (EDA) it is the first estimate of the wire of a net, and the start of Steiner tree heuristics such as iterated 1-Steiner. Running Prim's algorithm on all pairs takes time. The fast method on this page uses a fact about the L1 metric: some RMST uses only the edges from each point to a nearest point in each of eight octants around it. These at most edges can be found by sweeps in time, and Kruskal's algorithm then finds the tree in .
In plain words
You have pins on a chip and want to join them all with as little wire as possible, where each wire runs from pin to pin and its length is counted along the grid, across plus up.
The slow way compares every pair of pins. The fast way uses a trick. Stand at a pin and cut the plane around it into eight slices, like a pizza. In each slice you only need the nearest pin. A farther pin in the same slice is never needed, because the nearer pin is closer to it than you are.
So each pin has at most eight candidate wires, and each wire is found from both ends, which leaves at most four per pin. Sort these few wires by length and take them from the shortest, skipping any wire that joins pins that are already connected.
The problem
The input is a list of points with real coordinates. The L1 distance is . The output is a spanning tree of the points, a set of pairs that connects them, of least total L1 length. Points that coincide can be joined by edges of length 0 first, so assume the points are distinct.
For a point , the eight octants are the cones at bounded by the horizontal, vertical and diagonal lines through . They are made half open, so that each other point lies in exactly one octant of : octant holds the directions with angle in degrees. For two points, lies in an upper octant of (angles in ) or lies in an upper octant of , so it is enough to search the four upper octants of each point.
In the octant , the points have and , and the distance is . So the nearest point there is the one with the least among the points in a region bounded by two inequalities. The other three upper octants become this one after a swap or a sign change of the coordinates, which keep L1 distances.
The algorithm
RMST(points)- 1
join repeated points by edges of length 0 and keep one copy of each - 2
for each of the four upper octants do - 3
map the coordinates so that this octant becomes {x' > x, y' − x' ≥ y − x} - 4
sort the points by decreasing x, and make an empty tree over the ranks of y − x - 5
for each point p in this order: find the point q with the least x + y among the points in the tree with y − x ≥ y_p − x_p - 6
if q exists then add the edge (p, q) with length d(p, q) - 7
insert p into the tree at the rank of y_p − x_p with the value x_p + y_p - 8
sort the edges by length and run Kruskal's algorithm with a disjoint-set forest - 9
return the tree edges
The tree of lines L4 to L7 is a Fenwick tree that answers "least value among ranks at least " and takes inserts. The sweep goes in decreasing , so when is handled, the tree holds the points to its right. The details of ties decide which of the two edges of each octant is open: points of equal are inserted after their queries when the octant needs strictly, and a query asks for ranks above instead of at least it when the octant needs . The Yao graph is the same construction with cones of any angle in the Euclidean plane.
Example
Take the five points , , , and . The nearest point in each upper octant is:
| point | ||||
|---|---|---|---|---|
| (5) | (5) | none | none | |
| none | (5) | none | (4) | |
| (5) | none | none | none | |
| none | none | none | none | |
| (5) | none | none | (2) |
In the octant of , both and are at distance 5, and the tie goes to the lower index, . The point is in the octant of , because the direction has angle exactly 135 degrees. The graph has 7 distinct edges, out of the 10 pairs: of length 2, of 4, and , , , , of 5. Kruskal takes and , then , skips because and are now joined, and takes . The tree is
, , , , with total length 16.
Prim's algorithm on all 10 pairs also gives 16. The pairs that the octant graph left out, such as of length 10, are never needed.
Correctness
The proof shows the following.
- Octant lemma. If and lie in the same half-open octant of and , then . The proof is a short case analysis in the octant , and the open side of the octant is what makes the inequality strict.
- Short paths in the graph. By induction on the length of a pair, every pair is joined in the octant graph by a path whose edges are all at most .
- The MST survives. An exchange argument, as in the cycle property, turns any minimum spanning tree of all pairs into one that uses only edges of the octant graph, without making it longer. So the MST of the octant graph is an RMST.
- The sweep finds the neighbors. At the time is handled, the tree holds exactly the points of the region to the right of , and the query on ranks returns the least among those with large enough .
Proof: The graph of nearest neighbors in the half-open octants contains a rectilinear minimum spanning tree, and the sweep finds those neighbors in O(n log n) timefull
Let be a set of distinct points and . For a point and , the octant is the set of points whose direction from has angle in degrees. Every is in exactly one octant of . Let be the graph with an edge from each to one nearest point of in each non-empty upper octant , with any rule for ties.
Lemma 1 (octant lemma). Let with and . Then .
Proof. The swap and the reflections and keep L1 distances. These maps and their compositions take each half-open octant onto or onto : for example the swap maps onto , and the reflection in the axis maps onto . So it suffices to prove the lemma for these two cones. Put at the origin, and . In both cones , so , , and the hypothesis is . We split by the signs of and . The case and is impossible, since it gives .
Cone , where and :
- and : , since .
- and : , using and .
- and : , and by the hypothesis. So , using and .
Cone , where and :
- and : , since .
- and : , using and .
- and : as above , using and .
In all cases .
Lemma 2 (short paths). For every pair of points, has a path from to whose edges all have length at most .
Proof. By induction over the pairs in order of increasing . Swap the names if needed so that lies in an upper octant . Let be the neighbor of chosen in , so is an edge of and . If we are done. Otherwise Lemma 1 gives , so by induction has a path from to with edges at most . The edge followed by this path joins to with all edges at most . The induction is well founded because there are finitely many pairs.
Theorem 1 (the octant graph contains an RMST). Every minimum spanning tree of is a minimum spanning tree of the complete graph on with L1 lengths.
Proof. By Lemma 2, is connected. Let be a minimum spanning tree of the complete graph that has the most edges in . Suppose it has an edge not in . Removing splits into two parts, with in one and in the other. The path of Lemma 2 from to has an edge that joins the two parts, with length at most , and is in . Then is a spanning tree of length at most that of , so it is also minimum, and it has one more edge in . This contradicts the choice of . So lies in , and a minimum spanning tree of has length at most that of . It cannot be shorter, since it is also a spanning tree of the complete graph.
Lemma 3 (the sweep). After the map of line L3, the octant is the region or (with ), and in it . When the sweep handles , the Fenwick tree holds exactly the points with , or with and handled before , according to the octant, and the query returns the point with the least among those with in the right range.
Proof. For in the region, and , so both differences are non-negative and the L1 distance is their sum. The four maps take the octants , , and onto these regions, as a check of the inequalities shows. The sweep handles points by decreasing , with ties by decreasing . If the octant needs , a group of points with equal is inserted after all its queries, so the tree holds the points of larger . Otherwise each point is inserted right after its query, so the tree holds the points of larger and those of equal and larger , which with are exactly the points with . The query on ranks at least, or above, the rank of gives the right range of . Among these points the least is the nearest, by the formula for .
Running time. Line L1 takes with a sort or a hash table. Each of the four sweeps sorts points and makes queries and inserts in a Fenwick tree of size at most , so it takes . The graph has at most edges. Kruskal's algorithm sorts them in and makes disjoint-set operations. The space is .
Complexity
- Time. Each of the four sweeps sorts the points in and makes queries and inserts in a Fenwick tree, each . The graph has at most edges, so Kruskal's algorithm takes for the sort and nearly linear time for the disjoint-set operations. The total is .
- Lower bound. In the algebraic decision tree model, any RMST algorithm needs time, since the tree of points on a line gives their sorted order. So the bound is .
- Space. The edges, the tree and the sorted orders take space.
- Simple method. Prim's algorithm with an array, on all pairs, takes time and space. For nets of a few dozen pins it is just as good.
Properties
- What is proved. The algorithm returns a minimum spanning tree under the L1 metric for every input, in time.
- Degree. For distinct points, every RMST has at most one neighbor of in each half-open octant of , so its maximum degree is at most 8. If and were tree neighbors of in the same octant with , replacing the edge by would give a shorter spanning tree, by the octant lemma.
- Relation to Steiner trees. By Hwang's theorem, the RMST is at most 3/2 times the rectilinear Steiner minimum tree, and the ratio 3/2 is reached. So the RMST is a 3/2-approximation of the rectilinear Steiner tree problem.
- Not unique. With ties in length, many trees have the same total length. The tie rules of the sweep and of Kruskal fix the one returned.
Variants and improvements
- Voronoi diagram. Hwang (1979) built the L1 Voronoi diagram in time and took the MST from its dual graph, as in the Euclidean method from the Delaunay triangulation.
- Sweep with active sets. Zhou, Shenoy and Nicholls (2001) found the octant neighbors with a sweep that keeps, for each octant, the points whose neighbor in that octant is not yet found. The Fenwick tree sweep of this page is another way to answer the same queries.
- Other metrics. In the Euclidean plane, the Euclidean minimum spanning tree comes from the Delaunay triangulation. Yao (1982) used nearest neighbors in narrow cones for higher dimensions.
- Steiner trees. The RMST is the start of iterated 1-Steiner, of edge-based Steiner heuristics, and of the Prim-Dijkstra tradeoff.
When to use it
- To estimate the wire length of a net, or to start a Steiner tree heuristic, when the net has many pins.
- When an exact MST under L1 is needed for thousands or millions of points.
For nets with a few pins, Prim's algorithm on all pairs is simpler. For a better wire estimate use a Steiner tree, for example FLUTE, which is exact for small nets.
Pitfalls
- Closed octants. If both boundary rays of an octant are included, the octant lemma only gives : for , and all three distances are 2. The proof by induction then breaks. Make each octant half open, and handle points of equal or equal by the rule of the octant.
- Only four octants per point. The four upper octants of every point cover every pair once. Searching only the octant of each point, or only two octants, misses edges.
- Repeated points. Two points at the same place are in no octant of each other. Join them by edges of length 0 before the sweep.
- Euclidean intuition. The L1 metric is not the Euclidean metric. Methods that rely on Euclidean angles, such as the empty circle of the Delaunay triangulation, need the L1 versions.
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.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rectilinear-minimum-spanning-tree/. The authors are listed in prov/53V9N5.jsonl.
from bisect import bisect_left
from typing import Sequence
Point = tuple[int, int]
Edge = tuple[int, int, int] # (length, i, j)
def l1(p: Point, q: Point) -> int:
return abs(p[0] - q[0]) + abs(p[1] - q[1])
def region_neighbors(pts: Sequence[Point], strict_x: bool, strict_k: bool) -> list[int]:
"""For each point i, the point j that minimizes x_j + y_j among the points with
x_j >= x_i (or > if strict_x) and y_j - x_j >= y_i - x_i (or > if strict_k).
In that region the L1 distance from i is (x_j + y_j) - (x_i + y_i).
Returns -1 where the region is empty. Uses a sweep in decreasing x and a
Fenwick tree for suffix minima over the ranks of y - x. The points must be distinct.
"""
n = len(pts)
keys = sorted({y - x for x, y in pts})
m = len(keys)
inf = (float("inf"), -1)
tree = [inf] * (m + 1) # Fenwick tree over reversed ranks, holding minima
def update(rank: int, val: tuple) -> None:
i = m - rank
while i <= m:
if val < tree[i]:
tree[i] = val
i += i & -i
def query(rank: int) -> tuple: # minimum over ranks >= rank
i = m - rank
best = inf
while i > 0:
if tree[i] < best:
best = tree[i]
i -= i & -i
return best
order = sorted(range(n), key=lambda i: (-pts[i][0], -pts[i][1])) # @line L4
out = [-1] * n
g = 0
while g < n:
h = g
while h < n and pts[order[h]][0] == pts[order[g]][0]:
h += 1
group = order[g:h] # equal x, in decreasing y
for i in group:
x, y = pts[i]
r = bisect_left(keys, y - x)
best = query(r + 1 if strict_k else r) # @line L5
out[i] = best[1]
if not strict_x:
update(r, (x + y, i)) # @line L7
if strict_x:
for i in group:
x, y = pts[i]
update(bisect_left(keys, y - x), (x + y, i)) # @line L7
g = h
return out
# The four half-open octants [0, 45), [45, 90), [90, 135), [135, 180) degrees,
# each mapped onto a region of region_neighbors by an L1 isometry.
OCTANTS = (
(lambda x, y: (y, x), False, True),
(lambda x, y: (x, y), True, False),
(lambda x, y: (-x, y), False, True),
(lambda x, y: (y, -x), True, False),
)
def octant_graph(pts: Sequence[Point]) -> list[Edge]:
"""Edges from each distinct point to a nearest point in each of four half-open octants."""
edges = []
for f, sx, sk in OCTANTS: # @line L2
moved = [f(x, y) for x, y in pts] # @line L3
nb = region_neighbors(moved, sx, sk)
for i, j in enumerate(nb):
if j >= 0: # @line L6
edges.append((l1(pts[i], pts[j]), i, j))
return edges
def find(parent: list[int], a: int) -> int:
while parent[a] != a:
parent[a] = parent[parent[a]]
a = parent[a]
return a
def rectilinear_minimum_spanning_tree(points: Sequence[Point]) -> list[Edge]:
"""Return the edges (length, i, j) of a minimum spanning tree of points under the L1 metric.
Indices refer to the input list. Repeated points are joined by edges of length 0.
Runs in O(n log n) time.
"""
n = len(points)
first: dict[Point, int] = {}
edges: list[Edge] = []
uniq: list[int] = []
for i, p in enumerate(points): # @line L1
if p in first:
edges.append((0, first[p], i))
else:
first[p] = i
uniq.append(i)
sub = [points[i] for i in uniq]
for d, a, b in octant_graph(sub):
edges.append((d, uniq[a], uniq[b]))
edges.sort() # @line L8
parent = list(range(n))
tree = []
for d, a, b in edges:
ra, rb = find(parent, a), find(parent, b)
if ra != rb:
parent[ra] = rb
tree.append((d, a, b))
return tree # @line L9
test_rectilinear_minimum_spanning_tree.py 75 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rectilinear-minimum-spanning-tree/. The authors are listed in prov/53V9N5.jsonl.
import random
from rectilinear_minimum_spanning_tree import l1, octant_graph, rectilinear_minimum_spanning_tree
def prim_length(pts: list[tuple[int, int]]) -> int:
"""Prim's algorithm on the complete graph with L1 lengths, O(n^2)."""
n = len(pts)
if n == 0:
return 0
best = [l1(pts[0], p) for p in pts]
used = [False] * n
used[0] = True
total = 0
for _ in range(n - 1):
j = min((i for i in range(n) if not used[i]), key=lambda i: best[i])
used[j] = True
total += best[j]
for i in range(n):
if not used[i]:
best[i] = min(best[i], l1(pts[j], pts[i]))
return total
def is_spanning_tree(n: int, edges: list[tuple[int, int, int]]) -> bool:
if len(edges) != max(n - 1, 0):
return False
parent = list(range(n))
def find(a: int) -> int:
while parent[a] != a:
a = parent[a]
return a
for _, a, b in edges:
ra, rb = find(a), find(b)
if ra == rb:
return False
parent[ra] = rb
return True
EXAMPLE = [(0, 0), (4, 1), (1, 4), (5, 5), (2, 3)]
def test_example() -> None:
tree = rectilinear_minimum_spanning_tree(EXAMPLE)
assert sum(d for d, _, _ in tree) == 16
assert is_spanning_tree(5, tree)
assert len(octant_graph(EXAMPLE)) <= 4 * 5
def test_edges() -> None:
assert rectilinear_minimum_spanning_tree([]) == []
assert rectilinear_minimum_spanning_tree([(3, 3)]) == []
assert rectilinear_minimum_spanning_tree([(1, 1), (1, 1)]) == [(0, 0, 1)]
plus = [(1, 0), (0, 1), (2, 1), (1, 2)]
assert sum(d for d, _, _ in rectilinear_minimum_spanning_tree(plus)) == 6
line = [(i, 0) for i in range(6)]
assert sum(d for d, _, _ in rectilinear_minimum_spanning_tree(line)) == 5
def test_against_prim(seed: int = 19) -> None:
rng = random.Random(seed)
for _ in range(600):
n = rng.randint(1, 30)
span = rng.choice([3, 6, 20, 1000])
pts = [(rng.randint(-span, span), rng.randint(-span, span)) for _ in range(n)]
tree = rectilinear_minimum_spanning_tree(pts)
assert is_spanning_tree(n, tree)
assert all(d == l1(pts[a], pts[b]) for d, a, b in tree)
assert sum(d for d, _, _ in tree) == prim_length(pts)
History
The minimum spanning tree under the L1 metric was studied with the rectilinear Steiner problem in the 1960s and 1970s, when Hanan (1966) studied the rectilinear Steiner problem and Hwang (1976) bounded the ratio of the two trees. F. K. Hwang gave the first algorithm in 1979, by building the Voronoi diagram in the L1 metric. Andrew Yao showed in 1982 that the nearest neighbors of each point in a fixed set of cones contain a minimum spanning tree, which gave the graphs now called Yao graphs. Hai Zhou, Narendra Shenoy and William Nicholls presented a simple sweep for the octant neighbors in the L1 metric at ASP-DAC 2001, and the journal version appeared in Information Processing Letters in 2002.
References
- F. K. Hwang, An O(n log n) algorithm for rectilinear minimal spanning trees, Journal of the ACM 26(2), 177 to 182, 1979, the O(n log n) algorithm from the Voronoi diagram in the L1 metric
- Andrew Chi-Chih Yao, On constructing minimum spanning trees in k-dimensional spaces and related problems, SIAM Journal on Computing 11(4), 721 to 736, 1982, the lemma that the nearest neighbors of each point in a set of narrow cones contain a minimum spanning tree (general locator)
- Hai Zhou, Narendra Shenoy and William Nicholls, Efficient minimum spanning tree construction without Delaunay triangulation, Information Processing Letters 81(5), 271 to 276, 2002, the octant property of the L1 metric and the sweep that finds the octant neighbors in O(n log n) time
- Hai Zhou, Narendra Shenoy and William Nicholls, Efficient minimum spanning tree construction without Delaunay triangulation, Proceedings of ASP-DAC 2001, Yokohama, the conference version of the same method
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 53V9N5 Edit this page History Report an error Markdown