data-structures · intermediate · ~15 min

Shortest hop distance (BFS)

Unweighted shortest path via BFS.

Challenge

int bfs_distance(const int *adj,int n,int src,int dst);

Return the fewest edges on any path srcdst (BFS). src==dst → 0. Unreachable → −1.

Input format

adj n×n directed 0/1.

Output format

Hop count, or −1.

Constraints

BFS visits vertices in distance order.

Starter code

#include <stddef.h>
/* Fewest edges on a directed path from src to dst (BFS). Return the distance, or -1 if unreachable. src==dst -> 0. */
int bfs_distance(const int *adj,int n,int src,int dst){ (void)adj;(void)n;(void)src;(void)dst; return -1; }

Common mistakes

Using DFS (finds a path, not the shortest); forgetting the −1 case.

Edge cases to handle

src==dst → 0; unreachable → −1.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.