You are given an undirected graph and a source vertex. Your task is to determine the level of every vertex using Breadth First Search (BFS).
The level of a vertex is the minimum number of edges required to reach it from the source vertex.
Return -1 for vertices that are unreachable from the source.
Input: V = 5, edges = [[0,1],[0,2],[1,3],[2,4]], source = 0
Output: [0,1,1,2,2]
Explanation: Each value represents the minimum distance from the source vertex.
Input: V = 3, edges = [[0,1]], source = 0
Output: [0,1,-1]
Explanation: Vertex 2 is unreachable from the source.
Input: V = 1, edges = [], source = 0
Output: [0]
Explanation: The source vertex is at level 0.
Approach, complexity and clean code in every language. Sign in to unlock the editorial.
Your submissions, results and runtime history live here. Sign in to start your streak.
5 4 0 1 0 2 1 3 2 4 0
0 1 1 2 2
2 1 0 1 0
0 1