Typorithm · medium

Breadth-First Search

▷ Interactive algorithm labbreadth-first-searchsearchgraphqueueshortest-path-unweighted
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Breadth-First Search

0%

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.

Preparing algorithm lab…
01

Use a queue.

02

Mark nodes visited when discovered.

03

Explore neighbors level by level.

04

Works on adjacency lists.

05

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

Read the implementation

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

1. Queue

BFS explores nodes in first-in-first-out order.

const queue = [start]

2. Visited set

visited prevents cycles from repeating forever.

const visited = new Set([start])

3. Queue loop

Keep exploring while there are discovered nodes waiting.

while (queue.length > 0)

4. Dequeue

Take the oldest discovered node.

const node = queue.shift()

5. Target check

Return true when the current node is the target.

if (node === target) return true

6. Neighbors

Read neighbors from the adjacency list.

for (const neighbor of graph[node] ?? [])

7. Enqueue

Newly discovered neighbors wait behind older nodes.

queue.push(neighbor)

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.

Breadth-First Search: Visual Walkthrough & Practice · Typorithm | ApplyDjinn