AlgoFrames

Distance labels

Warm-up · Trace the algorithm · about 4 min

BFS runs from node 0 on this graph. Neighbors join the queue in increasing number order, and each new node gets its parent's distance plus 1.

Predict which node leaves the queue after node 0, then give the distance node 4 will get.

Example 1

Input:

{"n":7,"edges":[[0,1],[0,2],[1,3],[2,3],[3,4],[2,5],[5,6]],"directed":false,"source":0}

Output:

3

Node 4 is reached through 0, 1 or 2, then 3.

Constraints

  • The trace uses the graph shown

Learn the idea first: Shortest paths in unweighted graphs; path reconstruction, a visual lesson.

More Shortest paths in unweighted graphs; path reconstruction problems