Shortest path unweighted graph

Write codeMedium25 min

Your task

You are given an undirected graph with n nodes labeled 0..n-1 and an edge list. Each edge connects two nodes and is unweighted. Given a source node, return a list of length n where entry i is the shortest number of edges from the source to node i, or -1 if node i is unreachable. The source's own distance is 0. The graph may be disconnected and may contain multiple components; there are no self-loops and at most one edge between any pair.

Examples

bfs_distances(n: int, edges: list[list[int]], source: int) -> list[int]
Example 1
Inputbfs_distances(4, [[0, 1], [1, 2], [2, 3]], 0)
Output[0, 1, 2, 3]