Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Level of Each Node

Medium Acceptance 74.21% Points 30.00

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.

Examples
Example 1

image 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.

Example 2

image Input: V = 3, edges = [[0,1]], source = 0
Output: [0,1,-1]
Explanation: Vertex 2 is unreachable from the source.

Example 3

image Input: V = 1, edges = [], source = 0
Output: [0]
Explanation: The source vertex is at level 0.

Constraints
    • 1 = V = 105
    • 0 = E = 2 × 105
Companies
Oracle Paypal
Topics
Graph
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions