</>EmbeddedInterview

Find the shortest path in an unweighted graph using BFS.

MediumData Structures & Algorithms

Short answer: BFS discovers vertices in increasing hop distance. Save the distance and parent on first discovery.

#include <stdbool.h>
#define N 8

void shortest(const bool g[N][N], int start,
              int dist[N], int parent[N])
{
    int q[N], h = 0, t = 0;
    for (int i = 0; i < N; i++)
        dist[i] = parent[i] = -1;

    dist[start] = 0;
    q[t++] = start;
    while (h < t) {
        int u = q[h++];
        for (int v = 0; v < N; v++)
            if (g[u][v] && dist[v] == -1) {
                dist[v] = dist[u] + 1;
                parent[v] = u;
                q[t++] = v;
            }
    }
}

With edges 0→1→3 and 0→3, distance from 0 to 3 is 1. Follow parent links backward and reverse them to reconstruct the path; -1 means unreachable (except the source's parent). Assume a valid source. Time O(N²), space O(N).