1. Queue
BFS explores nodes in first-in-first-out order.
const queue = [start]Typorithm · medium
Step 1 of 8 · intro card
Search Algorithms
Breadth-First Search explores a graph level by level using a queue.
BFS starts from a node and explores all nearby nodes before going deeper.
A queue preserves discovery order.
A visited set prevents revisiting nodes in cycles.
For unweighted graphs, BFS finds the fewest-edge path to a target.
Use a queue.
Mark nodes visited when discovered.
Explore neighbors level by level.
Works on adjacency lists.
Time is O(V + E).
function breadthFirstSearch(graph, start, target) {
const queue = [start];
const visited = new Set([start]);
while (queue.length > 0) {
const node = queue.shift();
if (node === target) return true;
for (const neighbor of graph[node] ?? []) {
if (!visited.has(neighbor)) {
visited.add(neighbor);
queue.push(neighbor);
}
}
}
return false;
}Connect each part of the code to the concept before you type.
BFS explores nodes in first-in-first-out order.
const queue = [start]visited prevents cycles from repeating forever.
const visited = new Set([start])Keep exploring while there are discovered nodes waiting.
while (queue.length > 0)Take the oldest discovered node.
const node = queue.shift()Return true when the current node is the target.
if (node === target) return trueRead neighbors from the adjacency list.
for (const neighbor of graph[node] ?? [])Newly discovered neighbors wait behind older nodes.
queue.push(neighbor)Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputUndirected graph · start A · edges A–B:4, A–D:2, B–C:3, B–E:1, D–E:5, E–F:2, C–F:4
Follow temporary values, local state and supporting structures at this step.
No temporary values have been saved in this frame yet.
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state