Given an undirected graph represented as an adjacency list graph and a starting node start, return the level order traversal of its nodes' values, where the level of a node is its shortest-path distance (in edges) from start.
The graph has n nodes labeled from 0 to n - 1, and graph[i] is a list of all nodes directly connected to node i. Within each level, list nodes in increasing order of their values.
If a node is unreachable from start, it should not appear in the output.
Function Signature
def level_order(graph: list[list[int]], start: int) -> list[list[int]]:
...
Rules
-
Return a list of levels. Level
k
holds every node whose shortest-path distance from
start
is exactly
k
edges, so the first level is
[start]
.
-
A node's value is its label. The nodes inside each level are sorted in increasing order.
-
Levels appear in increasing order of distance. Unreachable nodes appear in no level.
Constraints
-
1 <= n <= 10^4
-
0 <= len(graph[i]) < n
-
0 <= graph[i][j] < n
-
0 <= start < n
-
The graph is undirected (if
j
is in
graph[i]
, then
i
is in
graph[j]
).
-
There are no self-loops or duplicate edges.
Examples
Input: graph = [[1,2],[0,3,4],[0,4],[1,5],[1,2,5],[3,4]], start = 0
Output: [[0],[1,2],[3,4],[5]]
The edges are 0-1, 0-2, 1-3, 1-4, 2-4, 3-5 and 4-5. Nodes 1 and 2 are one edge from 0, nodes 3 and 4 are two edges away, and node 5 is three edges away.
Input: graph = [[1],[0],[3],[2]], start = 0
Output: [[0],[1]]
The graph has two components, 0-1 and 2-3. Starting at 0 only reaches 0 and 1, so nodes 2 and 3 are excluded.
Input: graph = [[1,3],[0,4],[3],[0,2],[1]], start = 0
Output: [[0],[1,3],[2,4]]
Nodes 1 and 3 are adjacent to 0, node 4 hangs off node 1, and node 2 hangs off node 3. BFS discovers 4 before 2, but the last level is still listed in increasing order as [2,4].