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л. Dijkstra's algorithm: the shortest path in a mesh network and on a grid for a robot on static arrays

A node of a mesh network on BLE or LoRa decides through which neighbours to send a packet to the gateway. A robot cart decides how to drive around obstacles to its goal. Both tasks are a shortest path in a graph with edge costs, and both are solved by Dijkstra's algorithm. On a microcontroller it is written without a single malloc: the graph is constant arrays, the distances and the queue are static arrays, the queue is the binary heap from 76г with a position table.

Basis: alg.c with the heap-based algorithm and a scanning variant built with gcc 12.2.0 on the computer (stm-sys:1) — a mesh network of 12 nodes and a 16 × 16 grid with walls and "sand"; the answers of both variants agreed with each other and with an independent recomputation in Python. 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 comparisons when choosing the nearest node, not cycles.

Terms used in the documentation

Original Meaning
Dijkstra's algorithm Dijkstra's algorithm: shortest paths from one node with non-negative costs
edge weight, path cost edge cost, path cost
adjacency list (CSR) adjacency lists in compressed form: a node's edges in a row in one array
edge relaxation edge relaxation: a path through u is shorter — update the distance
predecessor array predecessor array: where the node was reached from
ETX, expected transmission count the expected number of transmissions over a link — the edge cost in mesh networks
hop count hop count: how many nodes are on the path
settled node settled node: its distance will not change any more

In plain words. Imagine water spreading in all directions from the start point, flowing along each edge at its own speed. Dijkstra each time takes the node the water reached first among those not yet flooded, and checks whether through it the water would reach the neighbours sooner than already known. A node the water has reached is not reconsidered: it cannot be reached any earlier.


76л.1 A graph on constant arrays

The graph is stored as compressed adjacency lists: all edges in a row in two arrays — where to and at what cost — and first[v] says where the edges of node v begin. There are no pointers, everything can live in flash:

typedef struct {
    uint16_t n;
    const uint16_t *first; /* n + 1 элементов */
    const uint16_t *to;
    const uint8_t *w;      /* цена ребра */
} graph_t;

The edges of node v run from first[v] to first[v + 1]. For a network of 12 nodes and 19 links this is 13 + 38 + 38 elements; for a 16 × 16 grid the graph is built from the cell map at start-up or after the map changes.


76л.2 The idea: settled nodes one by one

The distances of all nodes are "infinity", the start's is 0. Then in a loop: take the unsettled node with the smallest distance, declare it settled and relax its edges — if the path to a neighbour through it is shorter than the known one, write the new distance and the predecessor:

for (unsigned e = g->first[u]; e < g->first[u + 1]; e++) {
    uint16_t v = g->to[e];
    uint32_t nd = (uint32_t)dist[u] + g->w[e];
    if (nd < dist[v]) {
        dist[v] = (uint16_t)nd;
        prev[v] = u;
        pq_push_or_decrease(q, v);
    }
}

The sum is computed in uint32_t: "infinity" here is 0xFFFF, and adding a cost to it in uint16_t would overflow into a small number. The algorithm is correct only if the costs are non-negative — then a removed node really is settled. If the path is needed to only one goal, the loop is cut off as soon as that goal is removed: its distance will not change any more.


76л.3 The queue: a heap with a position table

The main operation is "take the nearest". Scanning all nodes costs n comparisons per step, n² for the whole algorithm. The heap from 76г gives the nearest in log n. But Dijkstra needs one more operation: the distance of a node already in the queue decreased — it must be raised. For this there is the same position table pos[] as for the timers in 76г.5:

static void pq_push_or_decrease(pq_t *q, uint16_t v)
{
    if (q->pos[v] == NONE) {
        q->h[q->n] = v;
        q->pos[v] = q->n;
        q->n++;
        if (q->n > q->peak)
            q->peak = q->n;
    }
    pq_up(q, q->pos[v]);
}

The heap key is not a copy of the distance but dist[v] itself: the heap stores node numbers and compares their distances through the key pointer. So a node is in the queue at most once, and n cells are enough for the heap.

The path is restored by predecessors from the goal back to the start:

for (uint16_t v = dst; v != NONE && k < max; v = prev[v])
    out[k++] = v;

76л.4 A mesh network: link cost against hop count

A network of 12 nodes, node 0 is the source, node 11 is the gateway. The link cost is the expected number of transmissions multiplied by 10: 10 is a lossless link, 30 means each packet has to be sent three times on average. The run:

Criterion path hops cost in ETX × 10
lowest cost 0 → 1 → 3 → 5 → 7 → 9 → 11 6 65
fewest hops 0 → 4 → 8 → 10 → 11 4 136

The fewest-hops path is twice as expensive: it goes through the poor long links 0 — 4 (cost 70) and 4 — 8 (45), where a packet is lost and resent. Six good hops are cheaper than four poor ones — both in time and in the energy of battery nodes. That is why mesh network protocols compute the route by link cost, not by hop count. Before the gateway the algorithm removed 11 nodes out of 12.

When link quality changes, the route is recomputed — for 12 nodes this is tens of operations, and it can be done even on every update of the neighbour table.


76л.5 A grid for a robot

A map of 16 × 16 cells: 52 walls, including a long one across the middle, and 49 cells of "sand", a step into which costs 5 instead of 1. A node is a cell, the edges are steps to the four neighbours:

A 16 × 16 grid: dark cells are walls, yellow ones are sand; the blue line is the found path from the top left corner to the bottom right, it goes around the long wall through the gap on the right and never enters sand; on the right — path cost 32, 33 cells in the path, 179 nodes removed before the goal out of 204 reachable, at most 24 in the heap at once

The cost of the found path is 32, the path has 33 cells, that is 32 steps of 1: the path never enters sand — going around is cheaper. Before the goal 179 nodes were removed out of 204 reachable, and the heap held no more than 24 nodes at once, although there was room for 256.

Memory: distances and predecessors at 2 bytes per cell and the heap with the position table at another 4 bytes, 8 bytes per node in total, 2048 bytes for 256 cells. For a chip with 20 KB of RAM this is tolerable, for 2 KB it is not; there the map is coarsened or the path is searched in sections.


76л.6 A heap or a scan

For a small graph a scan is simpler: no heap and no position table are needed. Comparisons when choosing the nearest, all nodes from the start:

Graph nodes heap scan
mesh network 12 21 156
16 × 16 grid 256 733 52480

At 12 nodes the difference is a hundred comparisons, and the scan is justified: 238 bytes of code instead of 398 + 122 and not a single extra array. At 256 cells the scan makes 256 comparisons on each of 205 steps — 72 times more than the heap. The distances of both variants agreed on all nodes.

Function code bytes M4 frame M4 code bytes M0 frame M0
dijkstra 398 56 460 56
pq_push_or_decrease 122 16 156 28
dijkstra_scan 238 48 260 56
path_back 52 4 44 12

76л.7 Limits and extensions

Limitation What to do
negative edge costs Dijkstra does not apply; in networks and maps costs are non-negative by meaning
the sum of costs exceeds 0xFFFE distances in uint32_t or a coarser cost unit
a path to a single goal on a large map is needed stop at the goal; better still — A*: Dijkstra with an estimate of the remaining path, removes fewer nodes
the graph changes often recompute it completely: for tens of nodes this is cheap
more nodes than RAM at 8 bytes per node coarsen the map, search in sections

76л.8 Links to other sections

The heap with a position table comes from 76г, where the same construction held timers. Compressed adjacency lists are related to the intrusive lists from 76е, only with indices in an array instead of pointers. And if the question is not "how to get there" but "are two nodes connected at all", Dijkstra is overkill — for that there is union-find from 76м.


76л.9 Pitfalls

A path "through infinity". The sum dist[u] + w was computed in uint16_t: 0xFFFF plus a cost overflowed into a small number, and an unreachable node turned out "close". Add in uint32_t.

Routing by hop count loses packets. All links cost 1, and the path went through poor long links: 136 against 65. The link cost is the expected number of transmissions.

The heap overflowed. A node was put into the queue on every distance improvement, without a position table, and one node sat in it many times. pos[] and raising a node already there — then n cells are enough.

The algorithm removed all nodes although one goal was needed. No stop at the goal: 204 removals instead of 179. Stop when the goal is removed.

RAM ran out on a large map. 8 bytes per node: 2048 bytes for 256 cells. Compute it in advance; on a small chip coarsen the map.


76л.10 Summary

Next: section 76м "Union-find: connectivity of network nodes and labelling regions in a binary image" — how to answer with one byte array whether two nodes are connected and number the blobs in a frame in two passes.

Open in the interactive handbook