Implement BFS algorithm

Pattern: BFS and DFS

medium

Breadth-first search from vertex 0: put it in a queue and mark it; repeatedly take the front vertex, record it, and add every unmarked neighbour to the back, marking it at once.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Given an adjacency list (adj[u] lists u's neighbours), return the BFS order starting from vertex 0, trying neighbours in the order listed. Only vertices reachable from 0 appear.

Think first

  • Which vertices come right after the start?
  • Why a queue?
  • When should a vertex be marked?

Hints

    Brute force, and why it fails

    Repeatedly scan all vertices for one at the next distance: O(V²).

    The key insight

    A queue naturally processes everything at distance d before distance d + 1.

    Dry run

    queue0

    adj = [[1, 2, 3], [0], [0, 4], [0], [2]]. Queue [0].

    Step 1 of 3

    The plan

    queue = [0]; seen = {0}
    while queue: u = pop front; out += u
      for v in adj[u]: if v not in seen: seen.add(v); push v
    

    Complexity

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

    Each vertex is queued once and each edge looked at once or twice.

    Edge cases

    • A single vertex with no edges.
    • A graph in several pieces.
    • Many edges at one vertex.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public List<Integer> bfsOfGraph(int[][] adj) {
            int n = adj.length;
            List<Integer> out = new ArrayList<>();
            boolean[] seen = new boolean[n];
            Queue<Integer> q = new ArrayDeque<>();
            q.add(0);
            seen[0] = true;                         // mark when added, so nothing is queued twice
            while (!q.isEmpty()) {
                int u = q.poll();
                out.add(u);
                for (int v : adj[u]) if (!seen[v]) { seen[v] = true; q.add(v); }
            }
            return out;
        }
    }

    C++

    class Solution {
    public:
        vector<int> bfsOfGraph(vector<vector<int>>& adj) {
            int n = static_cast<int>(adj.size());
            vector<int> out;
            vector<bool> seen(n, false);
            queue<int> q;
            q.push(0);
            seen[0] = true;                         // mark when added, so nothing is queued twice
            while (!q.empty()) {
                int u = q.front();
                q.pop();
                out.push_back(u);
                for (int v : adj[u]) if (!seen[v]) { seen[v] = true; q.push(v); }
            }
            return out;
        }
    };

    Python

    from collections import deque
    
    class Solution:
        def bfsOfGraph(self, adj: list[list[int]]) -> list[int]:
            out, seen, q = [], {0}, deque([0])      # mark when added, so nothing is queued twice
            while q:
                u = q.popleft()
                out.append(u)
                for v in adj[u]:
                    if v not in seen:
                        seen.add(v)
                        q.append(v)
            return out

    Common mistakes

    • Using a stack, which gives a DFS-like order.
    • Marking on removal, which can queue a vertex twice.

    Similar problems