AlgoLab
AlgorithmsCompare
AlgoLab
AlgorithmsCompareGitHub

© 2026 AlgoLab. Open source.

AlgorithmsGraphsBreadth-First Search
Graphsintermediategraphqueueshortest-pathunweighted

Breadth-First Search

BFS explores a graph level by level starting from a source node. Using a queue, it processes all nodes at distance 1, then distance 2, and so on. BFS finds the shortest path in unweighted graphs and is the basis for level-order tree traversal, bipartite checking, and web crawlers.

Complexity

Best
O(V+E)
Average
O(V+E)
Worst
O(V+E)
Space
O(V)

Visualizer

Implementation

void bfs(vector<vector<int>>& adj, int src, int n) {
    vector<bool> visited(n, false);
    queue<int> q;
    visited[src]=true; q.push(src);
    while (!q.empty()) {
        int v=q.front(); q.pop();
        cout << v << " ";
        for (int u : adj[v])
            if (!visited[u]) { visited[u]=true; q.push(u); }
    }
}

How It Works

1.Level-by-Level Exploration

BFS uses a queue (FIFO) to ensure nodes are processed in order of their distance from the source. All nodes at distance d are processed before any node at distance d+1.

2.Shortest Path

In an unweighted graph, the first time BFS reaches a node it has found the shortest path (minimum number of edges). Store parent pointers to reconstruct the path.

3.Visited Set

A visited set (or boolean array) prevents processing the same node twice. Without it, BFS would loop forever in graphs with cycles.

4.Applications

BFS is used for: shortest path in unweighted graphs, finding all nodes at distance k, checking if a graph is bipartite, finding connected components, and web crawlers.

Related Algorithms

Share2Depth-First SearchShare2Dijkstra's AlgorithmGitBranchLevel Order Traversal

Test Your Knowledge

1.

BFS uses which data structure?

2.

BFS on an unweighted graph finds:

3.

Time complexity of BFS is:

0/3 answered
Back to all algorithms