All algorithms
Graphs

Breadth-First Search (BFS)

Explore a graph level by level using a queue — shortest paths on unweighted graphs.

TimeO(V + E)SpaceO(V)CategoryGraphs

Breadth-First Search explores a graph outward in layers: it visits all neighbors of the start node first, then all of their unvisited neighbors, and so on. A queue holds the frontier — the nodes waiting to be processed — which is what gives BFS its level-by-level order.

Because it expands by distance, BFS finds the shortest path (in number of edges) on an unweighted graph. It is the backbone of flood fill, shortest-path-on-a-grid, and bipartite-checking problems.

AlgoLens renders the graph and the BFS queue together — you see which node comes out of the queue next and how the visited frontier grows, instead of guessing from printed output.

The code

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

int main() {
    int n, m;
    cin >> n >> m;

    vector<vector<int>> adj(n);
    for (int i = 0; i < m; i++) {
        int u, v;
        cin >> u >> v;
        adj[u].push_back(v);
        adj[v].push_back(u);
    }

    vector<int> dist(n, -1);
    queue<int> q;
    q.push(0);
    dist[0] = 0;

    while (!q.empty()) {
        int cur = q.front();
        q.pop();
        for (int nx : adj[cur]) {
            if (dist[nx] == -1) {
                dist[nx] = dist[cur] + 1;
                q.push(nx);
            }
        }
    }

    for (int d : dist) cout << d << ' ';
    cout << '\n';
    return 0;
}
Open this in the visualizer

Now run your own Breadth-First Search (BFS)

AlgoLens traces your code — arrays, graphs, trees and recursion — from a real execution, so you see how it actually behaves, not a canned animation.

Paste your code

Keep going