TExcelTAD
Home › Parameterized & Fine-Grained Complexity › Computing Treewidth and Elimination Orderings

Computing Treewidth and Elimination Orderings

Every algorithm of the treewidth section takes a tree decomposition as input. Finding one of minimum width is NP-hard (Arnborg, Corneil and Proskurowski, 1987), but for small width it is FPT, good approximations exist, and simple greedy heuristics produce useful decompositions in practice. This lesson states the main results and implements the heuristic side through elimination orderings, an equivalent and much more convenient description of tree decompositions.

Elimination orderings

To eliminate a vertex vv from a graph, make its neighbours pairwise adjacent (add "fill" edges) and delete vv. Eliminating all vertices in an order π=(v1,…,vn)\pi = (v_1, \ldots, v_n) produces a sequence of graphs; the width of π\pi is the largest degree a vertex has at the moment it is eliminated.

text
ELIMINATE(G, order)
1  width = 0
2  for v in order
3      N = current neighbours of v
4      width = max(width, |N|)
5      add an edge between every two vertices of N        // fill-in
6      delete v
7  return width

Theorem (stated; Bodlaender's survey, 1998, collects the equivalences). The treewidth of GG equals the minimum width over all elimination orderings.

The ordering also gives the decomposition. When vv is eliminated with current neighbourhood NN, create a bag {v}∪N\{v\} \cup N. Its parent is the bag of the vertex of NN that is eliminated first. Every edge, original or fill, lies in some bag, and the vertices of NN form a clique in the remaining graph, so they reappear together in the parent bag; this gives the connectivity condition. The bag sizes are the degrees plus one, so the decomposition has the width of the ordering.

Greedy heuristics

Two classical rules choose the next vertex greedily:

  • min-degree: eliminate a vertex of smallest current degree;
  • min-fill: eliminate a vertex whose elimination adds the fewest fill edges.

Neither is optimal in general, but both are fast and often close on sparse graphs; they are the default in many solvers for probabilistic inference and in database query optimizers. A matching lower bound comes for free: the degeneracy (largest minimum degree over all subgraphs, obtained by repeatedly deleting a vertex of minimum degree) is at most the treewidth, since a graph of treewidth tt always has a vertex of degree at most tt.

The program compares both heuristics with the degeneracy bound and, on small graphs, with the exact treewidth computed by a dynamic program over vertex subsets (the O∗(2n)O^*(2^n) algorithm of Bodlaender, Fomin, Koster, Kratsch and Thilikos, 2012): TW⁡(S)\operatorname{TW}(S) is the best width for eliminating the set SS first, and eliminating vv after SS costs the number of vertices outside S∪{v}S \cup \{v\} reachable from vv through SS.

python · try it yourself
import random
from functools import lru_cache

def eliminate_width(adj, rule):
    g = {v: set(nb) for v, nb in adj.items()}
    width, order = 0, []
    while g:
        def fill(v):
            nb = list(g[v])
            return sum(1 for i in range(len(nb)) for j in range(i + 1, len(nb)) if nb[j] not in g[nb[i]])
        key = (lambda v: (len(g[v]), v)) if rule == "degree" else (lambda v: (fill(v), len(g[v]), v))
        v = min(g, key=key)
        nb = g.pop(v)
        width = max(width, len(nb))
        for a in nb:
            g[a] |= nb - {a}
            g[a].discard(v)
        order.append(v)
    return width, order

def degeneracy(adj):
    g = {v: set(nb) for v, nb in adj.items()}
    best = 0
    while g:
        v = min(g, key=lambda x: (len(g[x]), x))
        best = max(best, len(g[v]))
        for a in g.pop(v):
            g[a].discard(v)
    return best

def exact_tw(adj):
    V = sorted(adj)
    def q(S, v):                                     # vertices outside S + v reachable from v via S
        seen, stack, out = {v}, [v], set()
        while stack:
            for u in adj[stack.pop()]:
                if u not in seen:
                    seen.add(u)
                    if u in S:
                        stack.append(u)
                    else:
                        out.add(u)
        return len(out)
    @lru_cache(maxsize=None)
    def tw(S):
        if not S:
            return 0
        return min(max(tw(S - {v}), q(S - {v}, v)) for v in S)
    return tw(frozenset(V))

def grid(r, c):
    adj = {v: set() for v in range(r * c)}
    for v in range(r * c):
        if v % c + 1 < c: adj[v].add(v + 1); adj[v + 1].add(v)
        if v + c < r * c: adj[v].add(v + c); adj[v + c].add(v)
    return adj

def gnp(n, p, seed):
    rng = random.Random(seed)
    adj = {v: set() for v in range(n)}
    for a in range(n):
        for b in range(a + 1, n):
            if rng.random() < p:
                adj[a].add(b); adj[b].add(a)
    return adj

tests = [("grid 3x4", grid(3, 4)), ("grid 2x6", grid(2, 6)), ("cycle 12", {v: {(v - 1) % 12, (v + 1) % 12} for v in range(12)})]
tests += [(f"G(12, 0.3) #{s}", gnp(12, 0.3, s)) for s in range(3)]
print("graph           degeneracy  min-degree  min-fill  exact")
for name, adj in tests:
    print(f"{name:15} {degeneracy(adj):10} {eliminate_width(adj, 'degree')[0]:11} {eliminate_width(adj, 'fill')[0]:9} {exact_tw(adj):6}")
graph           degeneracy  min-degree  min-fill  exact
grid 3x4                 2           3         3      3
grid 2x6                 2           2         2      2
cycle 12                 2           2         2      2
G(12, 0.3) #0            2           2         2      2
G(12, 0.3) #1            3           4         4      4
G(12, 0.3) #2            3           3         3      3

The heuristics and the lower bound sandwich the exact value; on these small graphs the heuristics hit it, while the degeneracy bound is sometimes one below. On larger grids min-degree does much worse, as the C++ program below shows: it eliminates low-degree vertices all over the grid and builds a ragged front.

From an ordering to a decomposition

The program turns the min-fill ordering of a random graph into a tree decomposition as described above and checks the three conditions.

python · try it yourself
import random

def gnp(n, p, seed):
    rng = random.Random(seed)
    adj = {v: set() for v in range(n)}
    for a in range(n):
        for b in range(a + 1, n):
            if rng.random() < p:
                adj[a].add(b); adj[b].add(a)
    return adj

def decomposition(adj, order):
    pos = {v: i for i, v in enumerate(order)}
    g = {v: set(nb) for v, nb in adj.items()}
    bags, parent = {}, {}
    for v in order:
        nb = g.pop(v)
        bags[v] = {v} | nb
        parent[v] = min(nb, key=pos.get) if nb else None
        for a in nb:
            g[a] |= nb - {a}
            g[a].discard(v)
    return bags, parent

def min_fill_order(adj):
    g = {v: set(nb) for v, nb in adj.items()}
    order = []
    while g:
        def fill(v):
            nb = sorted(g[v])
            return sum(1 for i in range(len(nb)) for j in range(i + 1, len(nb)) if nb[j] not in g[nb[i]])
        v = min(g, key=lambda x: (fill(x), len(g[x]), x))
        nb = g.pop(v)
        for a in nb:
            g[a] |= nb - {a}
            g[a].discard(v)
        order.append(v)
    return order

adj = gnp(30, 0.12, 4)
order = min_fill_order(adj)
bags, parent = decomposition(adj, order)
edges_ok = all(any(a in B and b in B for B in bags.values()) for a in adj for b in adj[a])
def connected(v):                                    # bags containing v must form a subtree
    holders = {u for u, B in bags.items() if v in B}
    roots = [u for u in holders if parent[u] not in holders]
    return len(roots) == 1
print("width", max(len(B) for B in bags.values()) - 1, "| bags", len(bags),
      "| edges covered", edges_ok, "| connectivity", all(connected(v) for v in adj))
print("roots of the decomposition forest:", [v for v in order if parent[v] is None])
width 7 | bags 30 | edges covered True | connectivity True
roots of the decomposition forest: [26]

The decomposition is a forest with one root per connected component of the graph; linking the roots in any way gives a tree.

In C++

Min-degree elimination with adjacency sets on a larger graph: a 15×1515 \times 15 grid, whose treewidth is 15. The program reports the width found and the number of fill edges added.

cpp · try it yourself
#include <cstdio>
#include <set>
#include <vector>

int main() {
    const int r = 15, c = 15, n = r * c;
    std::vector<std::set<int>> g(n);
    for (int v = 0; v < n; v++) {
        if (v % c + 1 < c) { g[v].insert(v + 1); g[v + 1].insert(v); }
        if (v + c < n) { g[v].insert(v + c); g[v + c].insert(v); }
    }
    std::vector<bool> gone(n, false);
    int width = 0;
    long fill = 0;
    for (int step = 0; step < n; step++) {
        int best = -1;
        for (int v = 0; v < n; v++)
            if (!gone[v] && (best < 0 || g[v].size() < g[best].size())) best = v;
        std::vector<int> nb(g[best].begin(), g[best].end());
        width = std::max(width, (int)nb.size());
        for (size_t i = 0; i < nb.size(); i++)
            for (size_t j = i + 1; j < nb.size(); j++)
                if (g[nb[i]].insert(nb[j]).second) { g[nb[j]].insert(nb[i]); fill++; }
        for (int a : nb) g[a].erase(best);
        g[best].clear();
        gone[best] = true;
    }
    std::printf("15 x 15 grid: min-degree width %d (treewidth 15), %ld fill edges\n", width, fill);
}
15 x 15 grid: min-degree width 22 (treewidth 15), 1188 fill edges

Exact and approximate algorithms (stated)

Result Time Authors
decide tw⁡≤t\operatorname{tw} \le t and find a decomposition 2O(t3)⋅n2^{O(t^3)} \cdot n Bodlaender (1996)
width at most 4t+34t + 3, or report tw⁡>t\operatorname{tw} > t O(33t t n2)O(3^{3t} \, t \, n^2) Robertson and Seymour (1995)
width at most 5t+45t + 4 2O(t)⋅n2^{O(t)} \cdot n Bodlaender, Drange, Dregi, Fomin, Lokshtanov and Pilipczuk (2016)
width at most 2t+12t + 1 2O(t)⋅n2^{O(t)} \cdot n Korhonen (2021)
exact, in time exponential in nn O∗(2n)O^*(2^n) (above); faster exponential bounds exist Bodlaender et al. (2012); Fomin, Kratsch, Todinca and Villanger (2008)
polynomial-time approximation factor O(log⁡tw⁡)O(\sqrt{\log \operatorname{tw}}) Feige, Hajiaghayi and Lee (2008)

Whether treewidth is NP-hard on planar graphs is a long-standing open question; the closely related branchwidth is polynomial on planar graphs (Seymour and Thomas, 1994). In practice, solvers from the PACE 2016 and 2017 challenges compute exact treewidth for graphs with hundreds of vertices when the width is moderate, combining heuristics like those above with clever exact search.

Test yourself

What does eliminating a vertex vv do?

  1. Deletes vv and its neighbours
  2. Makes the neighbours of vv pairwise adjacent and deletes vv
  3. Contracts vv into one neighbour
  4. Removes all edges between neighbours of vv

How is the treewidth related to elimination orderings?

  1. It is the maximum width over all orderings
  2. It is the minimum, over all orderings, of the largest degree of a vertex when it is eliminated
  3. It is the number of fill edges
  4. There is no relation

Why is the degeneracy a lower bound on the treewidth?

  1. Because every graph of treewidth tt, and every subgraph of it, has a vertex of degree at most tt
  2. Because degeneracy equals the clique number
  3. Because it is computed by min-fill
  4. It is an upper bound

Which statement about computing treewidth is correct?

  1. It is polynomial in general
  2. It is NP-hard in general but FPT: Bodlaender's algorithm decides tw⁡≤t\operatorname{tw} \le t in time 2O(t3)n2^{O(t^3)} n
  3. It is W[1]-hard
  4. It is undecidable