BFS Traversal - Problem
Given a graph represented as an adjacency list, implement Breadth-First Search (BFS) traversal starting from a given source node.
Return the traversal order as a list of integers. BFS explores nodes level by level, visiting all neighbors at the current depth before moving to nodes at the next depth level.
Note: The graph is represented as an adjacency list where graph[i] contains all neighbors of node i. Nodes are numbered from 0 to n-1.
Input & Output
Example 1 — Simple Connected Graph
$
Input:
graph = [[1,2],[0,3],[0],[1]], start = 0
›
Output:
[0,1,2,3]
💡 Note:
Starting at node 0, we first visit 0, then its neighbors 1 and 2 (level 1), then node 3 which is neighbor of 1 (level 2)
Example 2 — Linear Chain
$
Input:
graph = [[1],[0,2],[1,3],[2]], start = 0
›
Output:
[0,1,2,3]
💡 Note:
Linear chain 0-1-2-3: visit 0, then 1, then 2, then 3 in breadth-first order
Example 3 — Single Node
$
Input:
graph = [[]], start = 0
›
Output:
[0]
💡 Note:
Single isolated node with no neighbors, BFS returns just the start node
Constraints
- 1 ≤ graph.length ≤ 1000
- 0 ≤ graph[i].length ≤ 1000
- 0 ≤ graph[i][j] ≤ graph.length - 1
- 0 ≤ start < graph.length
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code