List of Induction problems

Posted on October 1, 2019
Tags: induction

1 Induction on queue

void bfs(int n, vector<vector<int>>& edgelist, vector<int>& dist, queue<int>& q) {
    
    for (int i : edgelist[n]) {
        if (dist[i] != -1) continue;
        dist[i] = dist[n] + 1;
        q.push(i);
    }
# invariant: top of queue is an immediate neighbor node of n
    if (!q.empty()) {
        n = q.front();
        q.pop();
        bfs(n, edgelist, dist, q);
    }
}

The topological ordering on the neighbors of n aka head of queue is the induction variable.

Front of Queue                                          End of Queue
n | neigh1_A | neigh1_B | neigh1_C | ... | neigh4_A | neigh4_B | ...

2 Examples