← DiffPush

Breadth First Search of a Graph

Baseline Graphs · Learning O(V + E) · O(V)

The Expanding Roll-Call Wave

A campus switchboard starts at the main desk (node 0) and announces a drill room by room in rings: first every room directly wired to the desk, then every room wired to those, and so on. Each room is called exactly once, and the announcement order is the moment each room first joins the wave — a queue keeps the rings honest.

Input: An integer V (number of vertices) and an adjacency list adj for a directed or undirected graph — adj[i] lists the neighbours of vertex i.

Output: Return the BFS order starting from vertex 0, restricted to nodes reachable from 0.

Constraints

Examples

Example 1

Input: {"V":5,"adj":[[1,2,3],[],[4],[],[]]}
Output: [0,1,2,3,4]
0 rings 1, 2, 3 first; 4 is reached when 2 is processed.

Example 2

Input: {"V":4,"adj":[[1,2],[2],[3],[]]}
Output: [0,1,2,3]
The wave walks the chain level by level.

Solve this in your browser →

Also on LeetCode ↗