Implement BFS
Standard · Write code · about 12 min
Given a graph and a source node, return the nodes reachable from source in the order breadth-first search takes them from the queue.
A node adds its unseen neighbors in increasing node number. Directed graphs follow edge direction. buildAdjacency(graph) returns the adjacency lists.
Example 1
Input:
[{"n":5,"edges":[[0,3],[0,1],[1,2],[3,4]],"directed":false},0]
Output:
[0,1,3,2,4]
Node 0 adds 1 before 3, so 2 comes before 4.
Example 2
Input:
[{"n":5,"edges":[[0,1],[0,2],[2,1],[1,3],[4,0]],"directed":true},0]
Output:
[0,1,2,3]
Node 4 points at 0 but cannot be reached from 0.
Constraints
- 1 ≤ n ≤ 200 nodes, numbered 0 to n - 1
- 0 ≤ source < n
- At most 3n edges; repeated edges and self-loops may appear
Learn the idea first: Breadth-first search, a visual lesson.
More Breadth-first search problems
- BFS order Warm-up
- Number of levels Warm-up
- Fewest edges between two nodes Standard
- Spot the bug: when to mark seen Standard
- BFS on a grid with walls Challenge