980. Level of Each Node from Source

EasyGraphsBFSGraph

Given an undirected graph with n nodes and a list of edges, return an array where entry i is the shortest distance (number of edges, the BFS level) from a given source to node i, or -1 if i is unreachable. The input is JSON {n, edges, src}.

Input: JSON {n, edges, src}.

Output: Array — the level of each node, or -1.

Examples

Example 1
Input: {"n":5,"edges":[[0,1],[0,2],[1,3],[2,4]],"src":0}
Output: [0,1,1,2,2]
Explanation: BFS levels from node 0.
Example 2
Input: {"n":4,"edges":[[0,1],[2,3]],"src":0}
Output: [0,1,-1,-1]
Explanation: Nodes 2,3 unreachable.
Example 3
Input: {"n":1,"edges":[],"src":0}
Output: [0]
Explanation: Only the source.

Constraints

Asked by

TCSInfosysWiproCognizantCapgemini
Solve this problem in the editor →