Given an undirected graph represented as an adjacency list graph and a starting node start, return the order in which nodes are visited using Breadth-First Search (BFS).
The graph is given as a list of lists, where graph[i] contains the neighbors of node i. When exploring neighbors of a node, visit them in the order they appear in the adjacency list. Only include nodes that are reachable from start.
BFS explores the graph level by level, visiting all neighbors of the current node before moving on to the next depth.
Function Signature
def bfs_traversal(graph: list[list[int]], start: int) -> list[int]:
...
Rules
-
Nodes are labeled
0
to
len(graph) - 1
, and
graph[i]
lists the neighbors of node
i
. The graph is undirected, so each edge appears in the lists of both of its endpoints.
-
When a node is taken from the queue, its unvisited neighbors are added in the order they appear in
graph[node]
. This order makes the expected output unique.
-
Each reachable node appears exactly once in the output. Nodes that cannot be reached from
start
are left out.
Constraints
-
1 <= len(graph) <= 10^4
-
0 <= len(graph[i]) < len(graph)
-
0 <= graph[i][j] < len(graph)
-
0 <= start < len(graph)
-
The graph is undirected and may be disconnected.
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. BFS visits 0, then its neighbors 1 and 2, then their unvisited neighbors 3 and 4 (both found from node 1), then 5.
Input: graph = [[1],[0,2],[1,3],[2]], start = 2
Output: [2,1,3,0]
The graph is the chain 0-1-2-3. Starting from 2, BFS visits 2, then 1 and 3 in the order node 2 lists them, then 0.
Input: graph = [[1],[0],[3],[2]], start = 3
Output: [3,2]
The graph has two components, 0-1 and 2-3. Nodes 0 and 1 cannot be reached from 3, so they are not in the output.