BFS Unweighted Shortest Path with Ancestor Tracking
Trees & GraphsAuto-graded · 21 test casesLast updated
Perform breadth-first traversal on an unweighted graph to compute shortest distances and record parent pointers for path reconstruction.
Given a directed or undirected unweighted graph with n vertices labeled from 0 to n - 1, represented as an adjacency list adj, perform a Breadth-First Search starting from a source node s.
Compute and return a list containing two arrays: [dist, parent].
dist: An array of lengthnwheredist[i]is the minimum number of edges needed to travel fromsto vertexi. If vertexiis not reachable froms,dist[i]should be-1. The distance to the starting nodesis0.parent: An array of lengthntracking the predecessor of each node on the discovered shortest path froms.parent[i]is the index of the vertex that first discoveredi. Ifi == soriis unreachable, setparent[i]to-1.
Constraints
- $1 \le n \le 10^5$
len(adj) == n- $0 \le s < n$
- $0 \le \text{adj}[u][i] < n$ for all valid $u, i$
- Total number of edges across all vertices is at most $2 \cdot 10^5$.
- Graphs may contain disconnected components, self-loops, or multiple edges.
Examples
Example 1
Input: bfs_shortest_paths(6, [[1, 2], [0, 3], [0, 3], [1, 2, 4], [3], []], 0)
Output: [[0, 1, 1, 2, 3, -1], [-1, 0, 0, 1, 3, -1]]
Example 2
Input: bfs_shortest_paths(5, [[1], [0, 2], [1], [4], [3]], 0)
Output: [[0, 1, 2, -1, -1], [-1, 0, 1, -1, -1]]
Example 3
Input: bfs_shortest_paths(4, [[], [], [], []], 2)
Output: [[-1, -1, 0, -1], [-1, -1, -1, -1]]
Hints
Hint 1
Initialize both the distance and parent arrays with -1 to handle unreachable nodes automatically.
Hint 2
Use a queue (e.g., `collections.deque`) for level-by-level traversal.
Hint 3
Mark nodes as visited as soon as you push them into the queue to avoid redundant processing and maintain linear time complexity.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
In an unweighted graph, all edge weights are equal to 1. Consequently, Breadth-First Search (BFS) naturally explores nodes in increasing order of their distance from the source vertex $s$.
-
Initialization:
- Initialize two arrays of size
n:distfilled with-1andparentfilled with-1. - The initial state at node
sis set todist[s] = 0. - Initialize a FIFO queue containing only
s.
- Initialize two arrays of size
-
Traversal:
- While the queue is non-empty, dequeue the front node
u. - Iterate through every neighbor
vinadj[u]. - If
vhas not been visited yet (indicated bydist[v] == -1):- Update
dist[v] = dist[u] + 1. - Set
parent[v] = u. - Enqueue
v.
- Update
- While the queue is non-empty, dequeue the front node
-
Termination:
- When the queue becomes empty, return
[dist, parent]. Unreachable nodes remain set to-1for both distance and parent values.
- When the queue becomes empty, return
Correctness & Efficiency
Setting dist[v] upon enqueueing ensures that each reachable node enters the queue exactly once. Because nodes are processed level by level, the first time node v is encountered gives the guaranteed shortest distance from $s$.
Complexity Analysis
- Time Complexity: $O(n + m)$ where $n$ is the number of vertices and $m$ is the total number of directed edges. Each node is enqueued once and each edge is traversed at most once.
- Space Complexity: $O(n)$ extra space to store the
distarray,parentarray, and the BFS queue.
from collections import deque
from typing import List
def bfs_shortest_paths(n: int, adj: List[List[int]], s: int) -> List[List[int]]:
dist = [-1] * n
parent = [-1] * n
dist[s] = 0
queue = deque([s])
while queue:
u = queue.popleft()
for v in adj[u]:
if dist[v] == -1:
dist[v] = dist[u] + 1
parent[v] = u
queue.append(v)
return [dist, parent]