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
INPUTALGORITHMRESULT0123Graph: [[1,2],[0,3],[0],[1]]Start: Node 01Start at node 02Add neighbors 1,2 to queue3Process queue: visit 1,24Add neighbor 3 to queueQueue: [0] → [1,2] → [3]BFS Order[0, 1, 2, 3]Level 0: Node 0Level 1: Nodes 1, 2Level 2: Node 3Key Insight:BFS uses a queue to ensure level-by-level traversal, visiting all nodes at distance k beforeany nodes at distance k+1. This guarantees shortest path exploration in unweighted graphs.TutorialsPoint - BFS Traversal | Queue-Based Approach
Asked in
Google 45 Amazon 38 Facebook 32 Microsoft 28
23.4K Views
High Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen