Algo-Sim › Graph Traversal

Breadth-First Search

Easy · Graph Traversal · step through it in Java, Python and C++ on your own input

Visit every node reachable from start, nearest first, using a queue. In an unweighted graph this finds shortest paths.

Problem

An undirected graph has nodes 0..n − 1 and the given edges. Starting from start, list every reachable node in breadth-first order: all nodes one edge away, then two edges away, and so on. Neighbours are taken in increasing order.

Constraints

Edge cases to test

Follow-up questions

How do you get the shortest path itself?
Record each node’s parent when it is first enqueued and walk back from the target: O(V + E).
Why mark nodes when enqueued, not when dequeued?
Otherwise one node can be enqueued many times, which costs extra time and memory.
What if edges have weights 0 or 1?
0-1 BFS with a deque: weight-0 edges go to the front, weight-1 to the back: O(V + E).

Solution

Java

public List<Integer> bfs(List<List<Integer>> adj, int start) {
    List<Integer> order = new ArrayList<>();
    boolean[] visited = new boolean[adj.size()];
    Queue<Integer> queue = new ArrayDeque<>();
    visited[start] = true;
    queue.offer(start);
    while (!queue.isEmpty()) {
        int node = queue.poll();
        order.add(node);
        for (int next : adj.get(node)) {
            if (!visited[next]) {
                visited[next] = true;
                queue.offer(next);
            }
        }
    }
    return order;
}

Python

from collections import deque


def bfs(adj, start):
    order = []
    visited = [False] * len(adj)
    queue = deque()
    visited[start] = True
    queue.append(start)
    while queue:
        node = queue.popleft()
        order.append(node)
        for neighbor in adj[node]:
            if not visited[neighbor]:
                visited[neighbor] = True
                queue.append(neighbor)
    return order

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    vector<int> bfs(vector<vector<int>> &adj, int start) {
        vector<int> order = {};
        vector<bool> visited = vector<bool>(int(adj.size()));
        deque<int> queue = {};
        visited[start] = true;
        queue.push_back(start);
        while (!queue.empty()) {
            int node = queue.front();
            queue.pop_front();
            order.push_back(node);
            for (int next : adj[node]) {
                if (!visited[next]) {
                    visited[next] = true;
                    queue.push_back(next);
                }
            }
        }
        return order;
    }
};

More Graph Traversal problems