Skip to the page

Graphs and grids · mid

Matrix and grid BFS in JavaScript

A grid is a graph where each cell links to its 4 (or 8) neighbours, so islands, flood fill and 'spread' problems are BFS or DFS with bounds checks and a visited mark. In JavaScript, use an explicit queue to avoid stack overflow, and build 2D arrays with Array.from so rows are not shared.

The notes

What you must know

  • Directions array: [[1,0],[-1,0],[0,1],[0,-1]] (add diagonals for 8-way, e.g. minesweeper).
  • Bounds check before reading: r >= 0 && r < rows && c >= 0 && c < cols.
  • Mark visited when enqueuing. You may mutate the grid ('1' → '0') only if the interviewer allows; otherwise keep a visited array or Set of r * cols + c.
  • Multi-source BFS: put all sources in the queue at time 0 (rotting oranges, distance to nearest exit).
  • Recursive DFS on a 1000×1000 grid can exceed the stack in JavaScript; use an explicit queue/stack.
  • Flood fill: if the new colour equals the old colour, return early, or you loop forever. On a real canvas, work on ImageData with a Uint32Array.
  • Build a 2D array with Array.from({ length: rows }, () => new Array(cols).fill(false)). new Array(rows).fill(new Array(cols).fill(false)) puts one shared row in every slot, so marking one cell marks the whole column. A flat Uint8Array(rows * cols) indexed by r * cols + c is smaller and faster.

The red pen

Common traps: mistake → fix

  • Mistake: Recursion is fine for grids

    Fix: one long snake-shaped island is a million frames deep.

  • Mistake: Mark visited when you pop

    Fix: the same cell is queued many times.

  • Mistake: Flood fill with same colour just does nothing

    Fix: without the early return it loops forever.

  • Mistake: fill() with an array makes separate rows

    Fix: every slot points to the same row.

Easy to hard

Questions interviewers ask, easy to hard

  1. Count islands.
  2. Flood fill from a clicked pixel (paint bucket).
  3. Minutes until all oranges rot (multi-source BFS).
  4. Minesweeper: reveal empty regions; why might recursion fail on a big board?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview