Skip to problem
←

Breadth-First Search of a Graph

Easy 0 attempts

You're given a directed graph described as an adjacency list adj, where adj[i] lists the nodes reachable directly from node i. Starting from node 0, return the order in which nodes are visited by a breadth-first traversal.

Inspect each vertex’s neighbors in the order listed in adj. Visit each vertex at most once and omit vertices that cannot be reached from 0.

Function contract

Implement bfsOfGraph(adj), where adj[v] lists the outgoing neighbors of vertex v. Vertex labels are 0 through adj.length - 1.

Output: An array of visited vertex labels in BFS order starting at 0. Inspect neighbors in their listed order; omit unreachable vertices.

Example 1

Input
adj = [[1,2],[3],[4],[],[]]
Output
[0,1,2,3,4]

Example 2

Input
adj = [[1],[],[]]
Output
[0,1]
Visual Aid
Visit one level at a time
01234BFS order: 0, 1, 2, 3, 4

For example 1, visit 0 first, then its neighbors 1 and 2, then 3 and 4.

Constraints
  • 1 <= adj.length <= 10^4
  • 0 <= total number of listed edges <= 10^4
  • Each neighbor is an integer from 0 to adj.length - 1.
Topics

Standard BFS

Use a queue and visited set to traverse level by level.

javascript
function bfsOfGraph(adj) {
  const visited = new Set([0]), q = [0], result = [];
  let head = 0;
  while (head < q.length) {
    const node = q[head++];
    result.push(node);
    for (const next of adj[node]) {
      if (!visited.has(next)) { visited.add(next); q.push(next); }
    }
  }
  return result;
}

Time: O(V + E) | Space: O(V)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript