Skip to content
DSA in JavaScript
← All patterns

Breadth-First Search

0/18 solved

What it is

Explore level by level using a queue: everything one step away, then everything two steps away, and so on.

Used for

Shortest path in an unweighted graph or grid, level-order traversal, minimum number of steps.
791152Level 1Level 2Level 3

queue: 7

Step 1 of 5

Goal: find the fewest steps from the start to everything else. Breadth-first search explores in rings: everything one step away, then everything two steps away. It uses a queue, a line where the first one in is the first one out.

You see

  • Shortest path in an unweighted graph or grid
  • Level-by-level processing
  • Minimum number of steps or moves

Learn it in

QueueBreadth-First Search (graph)Breadth-First Search (tree)

Template

function levelOrder(root) {  const out = [], q = root ? [root] : [];  while (q.length) {    const level = [];    for (let n = q.length; n > 0; n--) {      const node = q.shift();      level.push(node.val);      node.left && q.push(node.left);      node.right && q.push(node.right);    }    out.push(level);  }  return out;}

Practice problems