You are given an undirected graph with n nodes labeled from 0 to n - 1, represented by a list of edges where each edges[i] = [u, v] indicates an undirected edge between nodes u and v.
Starting from node start, perform a Breadth-First Search (BFS) traversal of the graph and return the order in which the nodes are visited.
When exploring neighbors of a node, visit them in ascending order of their labels. If a node is unreachable from start, it should not appear in the result.
Function Signature
def bfs_traversal(n: int, edges: list[list[int]], start: int) -> list[int]:
...
Rules
-
Each
[u, v]
in
edges
is an undirected edge, so
v
is a neighbor of
u
and
u
is a neighbor of
v
.
-
When a node is taken from the queue, its unvisited neighbors are added to the queue in ascending order of their labels. The ordering applies to each node's own neighbors: a node discovered earlier still leaves the queue earlier, even if its label is larger.
-
Nodes that cannot be reached from
start
are left out of the result.
Constraints
-
1 <= n <= 10^4
-
0 <= len(edges) <= 2 * 10^4
-
len(edges[i]) == 2
-
0 <= edges[i][0], edges[i][1] < n
-
0 <= start < n
Examples
Input: n = 6, edges = [[0,1],[0,2],[1,3],[1,4],[2,5]], start = 0
Output: [0,1,2,3,4,5]
The graph is a tree rooted at 0, with children 1 and 2, nodes 3 and 4 under 1, and node 5 under 2. BFS visits 0, then 1 and 2, then 3, 4 and 5.
Input: n = 5, edges = [[0,1],[2,3],[3,4]], start = 2
Output: [2,3,4]
The graph has two components, 0-1 and 2-3-4. BFS from 2 stays inside its own component, so nodes 0 and 1 are not in the result.
Input: n = 5, edges = [[0,4],[0,2],[4,1],[2,3]], start = 0
Output: [0,2,4,3,1]
Node 0's neighbors are taken in ascending order, 2 before 4, even though the edge to 4 is listed first. Node 3 comes before node 1 because it is discovered from node 2, which leaves the queue before node 4.