Embedded HandbookApps
All sections › IX. The C language: from basics to advanced
STM32F103, STM32F407, STM32G031 · level intermediate · 8 min read
Open in the interactive handbook

76м. Union-find: connectivity of network nodes and labelling regions in a binary image

Sometimes what is needed from a graph is not a path, as in 76л, but a single answer: are two nodes connected at all. Has any route at all reached node 8 from node 0? How many separate blobs are there in a frame from an image sensor? For this there is the "union-find" structure: it keeps a partition of nodes into groups, merges two groups in a few steps and answers whether two nodes are in the same group. The whole thing is one byte array, and with path compression its operations hardly depend on the number of nodes.

Basis: alg.c with union-find and two-pass region labelling built with gcc 12.2.0 on the computer (stm-sys:1) — a network of 16 nodes with links appearing one by one, a worst-case chain of 200 nodes with search with and without compression, labelling of a 32 × 24 frame. The number and areas of the regions are recomputed in Python by breadth-first search. The same file built with arm-none-eabi-gcc 12.2.1 (stm-arm:1) at -O2 for Cortex-M4F and Cortex-M0 — sizes and frames. Work is expressed as the number of steps along links, not cycles.

Terms used in the documentation

Original Meaning
union-find, disjoint-set forest union-find, a forest of disjoint sets
find, union find the representative of a group; merge two groups
path compression, path halving path compression; halving the path on every search
union by size union by size: the smaller tree goes under the larger
connected components connected components: groups of nodes linked with each other
connected-component labelling labelling the connected regions of an image
4-connectivity, 8-connectivity neighbours by sides; by sides and corners
provisional label, equivalence a provisional label; equivalence of labels of one region

In plain words. Each node has a "boss", and the top boss of a group is his own boss. To find out the group, you walk up the bosses to the very top. To merge two groups, it is enough for one top boss to start reporting to the other. And so that the chains do not grow, on the way up everyone met is reassigned closer to the top boss — next time the path will be shorter.


76м.1 The structure: an array of parents

Each node stores its parent's number; a root is its own parent. A group is a tree, its representative is the root. For 256 nodes bytes are enough:

typedef struct {
    uint8_t parent[UF_MAX]; /* корень множества указывает сам на себя */
    uint8_t size[UF_MAX];   /* размер множества — только у корня */
    uint16_t sets;
} uf_t;

That is 512 bytes for 256 nodes — and no pointers, lists or malloc. The sets counter is how many groups there are now.


76м.2 Find with path compression

Finding the root means climbing through the parents. Without tricks a tree can degenerate into a chain, and a search becomes a scan. Path compression makes every search useful for the following ones: on the way up each node is rehung on its grandparent. The path is halved, and all of it — without recursion (76и), in one loop:

unsigned uf_find(uf_t *u, unsigned x)
{
    while (u->parent[x] != x) {
        STEP_HOOK();
        u->parent[x] = u->parent[u->parent[x]];
        x = u->parent[x];
    }
    return x;
}

A run on the worst case — a chain of 200 nodes where each hangs on the next:

Search from the end of the chain 1st time 2nd time 10th time
without compression 199 steps 199 steps 199 steps
with halving 100 steps 50 steps 1 step

Without compression every search is 199 steps. With compression the first search is 100, the second 50, by the tenth — one step: the tree has become almost flat. On M4 uf_find is 24 bytes and 12 instructions.


76м.3 Union by size

The second defence against long chains is to hang the smaller tree under the larger on a merge. Then the depth of any tree is at most log₂ n, even without compression, and together with compression the operations take a few steps in practice for any n:

a = uf_find(u, a);
b = uf_find(u, b);
if (a == b)
    return false;
if (u->size[a] < u->size[b]) {
    unsigned t = a;
    a = b;
    b = t;
}
u->parent[b] = (uint8_t)a;

uf_union returns false if the nodes were already in one group: the new edge connected nothing, it closes a cycle. That is a useful answer in itself — see 76м.4.

The size in a byte saturates at 255; for a tree of 256 nodes this is enough to choose correctly which goes under which — the exact size of large groups does not need to be compared.


76м.4 Connectivity of network nodes

Mesh network nodes report their neighbours, and links appear one by one. The run: 16 nodes, 15 links. After all links 2 groups remained: nodes 0 and 7 are connected, 0 and 8 are not, 8 and 14 are connected. One link out of 15 — between 0 and 2 — turned out redundant: uf_union returned false because 0 and 2 were already connected through 1 and 3.

What this is used for:

Question The structure's answer
will a packet get from A to B by any path at all uf_find(A) == uf_find(B)
how many separate islands the network has sets
which links can be switched off without losing connectivity those on which uf_union returned false
a cycle-free tree of links for broadcasting take links from best to worst and keep those uf_union accepted (Kruskal's algorithm)

A limitation: union-find can only merge. If a link disappears, a group cannot be split — the structure is rebuilt from the current list of links. For 16 nodes that is 16 initialisations and one union per link.


76м.5 Labelling regions in a binary image

A frame from an image sensor after thresholding is pixels "on" and "off". The task is to number the connected blobs: count the objects, find their areas and centres. The flood fill from 76и does this, but needs a stack. Union-find gives an algorithm in two passes with memory known in advance.

The first pass goes row by row. A pixel looks at its neighbours above and to the left: no labelled neighbours — a new provisional label; there are — take the neighbour's label; and if the labels above and to the left differ, it is one region, and the labels are united:

unsigned up = y ? lab[y - 1][x] : 0, left = x ? lab[y][x - 1] : 0;
if (!up && !left) {
    if (next == UF_MAX)
        return -1;
    lab[y][x] = (uint8_t)next++; /* новая временная метка */
} else {
    lab[y][x] = (uint8_t)(up ? up : left);
    if (up && left && up != left)
        uf_union(u, up, left); /* две метки оказались одной областью */
}

The second pass replaces every provisional label with the label of its group's root and renumbers the roots consecutively.

A 32 × 24 frame: a green letter U with a noise pixel stuck to it, a blue rectangle, a yellow checkerboard of separate cells at the bottom right and noise pixels; captions: the letter U is 87 pixels, the rectangle 80, 59 small regions, 56 of them single pixels; the first pass gave 63 provisional labels

A run on a frame with the letter U, a rectangle, a checkerboard and twelve noise pixels: 231 pixels, 63 provisional labels, 61 regions. The legs of the letter U got different labels — they are not connected at the top — and merged when the first pass reached its bottom. There are two large regions — 87 and 80 pixels — and 56 single-pixel regions. The number and areas of the regions agreed with an independent breadth-first search in Python. All the finds of both passes took 52 steps along links.


76м.6 4 or 8 neighbours

The checkerboard at the bottom right is 54 pixels touching each other only at the corners. With 4 neighbours each of them is a separate region, hence most of the 56 single ones. With 8 neighbours — when the neighbours above-left and above-right are also checked — the checkerboard would become one region. Which connectivity is right is decided by the task: for counting parts on a conveyor it is usually 8, for separating objects that touch at corners — 4. In the code the difference is two additional neighbours in the first pass.


76м.7 Memory and code

What M4 M0
uf_find, code bytes 24 24
uf_union, code bytes 120 132
label_regions, code bytes 298 356
label_regions, stack frame 312 312

RAM: the labels of a 32 × 24 frame take 768 bytes, the parents and sizes 512. The label_regions frame is 312 bytes: it holds the renumbering table for 256 labels. There are at most 255 provisional labels — byte numbers; if labels run out, the function returns −1 instead of writing past the end. For larger frames the labels are made uint16_t, and the frame is processed in strips.


76м.8 Union-find, flood fill or Dijkstra

Task What to take
are two nodes connected, how many groups, links appear one by one union-find
a path and its cost between two nodes Dijkstra (76л)
one region from a given point scanline fill (76и)
all regions of a frame, memory known in advance two-pass labelling with union-find
links both disappear and appear rebuilding union-find or a graph walk

76м.9 Pitfalls

Search became slow. The trees degenerated into chains: without compression a search in a chain of 200 nodes takes 199 steps every time. Path compression and union by size.

A recursive find with compression crashed the stack. The classic form of compression is recursion as deep as the chain is long. Halving in a loop does the same without a stack.

The checkerboard counted fifty objects. Connectivity by 4, while the object touches itself at corners. Choose the connectivity for the task.

The labels ran out. On a noisy frame there are more than 255 provisional labels. Check the limit and return an error; uint16_t labels or suppress the noise before labelling.

A link disappeared, but the nodes are still "connected". Union-find cannot split groups. Rebuild from the current links.


76м.10 Summary

Next: section 77 "Compilation and compilers".

Open in the interactive handbook