Typorithm · medium

Graph BFS

▷ Interactive algorithm labgraph-bfsgraph-algorithmsqueuevisited-setlevels
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Graph BFS

0%

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.

Preparing algorithm lab…
01

Queue gives level order.

02

Mark visited on enqueue.

03

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;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Mark on enqueue

Mark a node visited the moment it enters the queue, not when it leaves.

const visited = new Set([start])

2. FIFO frontier

A queue processes nodes oldest-first, giving level-by-level order.

const queue = [start]

3. Dequeue

Take the front node to expand its neighbors.

const node = queue.shift()

4. Skip visited

Never enqueue a node that is already seen.

if (!visited.has(next))

5. Enqueue neighbor

Add unseen neighbors to the back of the queue.

queue.push(next)

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Graph BFS: Visual Walkthrough & Practice · Typorithm | ApplyDjinn