Breadth-First Search (BFS) explained: level-order graph & tree traversal, queue implementation, shortest path in unweighted graphs.
Breadth-First Search (BFS) explores nodes outward in concentric levels from a starting vertex. Using a FIFO Queue, BFS ensures that all nodes at distance d are processed before any node at distance d + 1.
Because BFS visits nodes in increasing order of distance, it guarantees finding the shortest path in unweighted graphs or uniform-cost grids.
Enqueue the starting node into a FIFO queue and mark it as visited.
Remove the front element from the queue and add it to the traversal path.
Iterate through all adjacent neighbors of the current node. For each unvisited neighbor, mark it visited and push it into the queue.
Continue dequeuing and visiting neighbors until no nodes remain in the queue.
1function bfs(graph, startNode) {2 const visited = new Set([startNode]);3 const queue = [startNode];4 const result = [];5 6 while (queue.length > 0) {7 const node = queue.shift(); // Dequeue front8 result.push(node);9 10 const neighbors = graph[node] || [];11 for (const neighbor of neighbors) {12 if (!visited.has(neighbor)) {13 visited.add(neighbor);14 queue.push(neighbor); // Enqueue15 }16 }17 }18 19 return result;20}21 22// Example usage:23// const graph = { A: ['B', 'C'], B: ['D'], C: ['E'], D: [], E: [] };24// bfs(graph, 'A'); // ['A', 'B', 'C', 'D', 'E']Play through every comparison, swap, and state change, adjust the speed, or enter custom inputs to test edge cases.
The full interactive roadmap is unlocking — these specialized modules land in upcoming releases.
This feature will be implemented in the next update.
This feature will be implemented in the next update.
This feature will be implemented in the next update.
Explore the full catalog — 30+ algorithms with more unlocking every release.
Interactive node & edge state graph traversal explorer
Test your understanding of Breadth-First Search (BFS) complexity and step mechanics.
Q1.Which data structure does Breadth-First Search rely on?
Q2.Why is BFS guaranteed to find the shortest path in an unweighted graph?
Apply Breadth-First Search (BFS) to real coding interview questions.
Find the shortest transformation sequence length from beginWord to endWord.
Find the minimum number of minutes that must elapse until no cell has a fresh orange.