1. Mark on enqueue
Mark a node visited the moment it enters the queue, not when it leaves.
const visited = new Set([start])Typorithm · medium
Step 1 of 8 · intro card
Graph Algorithms
Explore a graph level by level with a FIFO queue, marking nodes visited as they are enqueued.
BFS visits all neighbors of a node before going deeper, expanding outward in rings.
A visited set prevents revisiting and, marked on enqueue, stops a node entering the queue twice.
In an unweighted graph, the first time BFS reaches a node is along a shortest path.
Queue gives level order.
Mark visited on enqueue.
First reach is shortest (unweighted).
function bfs(graph, start) {
const visited = new Set([start]);
const queue = [start];
const order = [];
while (queue.length > 0) {
const node = queue.shift();
order.push(node);
for (const next of graph[node]) {
if (!visited.has(next)) {
visited.add(next);
queue.push(next);
}
}
}
return order;
}Connect each part of the code to the concept before you type.
Mark a node visited the moment it enters the queue, not when it leaves.
const visited = new Set([start])A queue processes nodes oldest-first, giving level-by-level order.
const queue = [start]Take the front node to expand its neighbors.
const node = queue.shift()Never enqueue a node that is already seen.
if (!visited.has(next))Add unseen neighbors to the back of the queue.
queue.push(next)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