Number of levels
Warm-up · Fill in the code · about 6 min
Complete countLevels(graph, source). It returns how many levels (rings) BFS finds from source, counting level 0. Only reachable nodes count.
Fill the three blanks.
Example 1
Input:
[{"n":5,"edges":[[0,3],[0,1],[1,2],[3,4]],"directed":false},0]
Output:
3
Levels 0, 1 and 2.
Example 2
Input:
[{"n":6,"edges":[[0,1],[1,2],[2,3],[3,4],[4,5]],"directed":false},0]
Output:
6
A path of 6 nodes has 6 levels.
Constraints
- 1 ≤ n ≤ 200 nodes, numbered 0 to n - 1
- 0 ≤ source < n
- At most 3n edges; repeated edges and self-loops may appear
Learn the idea first: Breadth-first search, a visual lesson.
More Breadth-first search problems
- BFS order Warm-up
- Implement BFS Standard
- Fewest edges between two nodes Standard
- Spot the bug: when to mark seen Standard
- BFS on a grid with walls Challenge