Skip to the page

Graphs and grids · mid

Matrix and grid BFS

A grid is a graph where each cell links to its 4 (or 8) neighbours, so islands, flood fill, minesweeper reveal and 'spread' problems are BFS or DFS with bounds checks and a visited mark, done with a queue or stack to avoid deep recursion.

The notes

What you must know

  • Directions array: [[1,0],[-1,0],[0,1],[0,-1]] (add the diagonals for 8-way moves, for example minesweeper).
  • Bounds check before reading: r >= 0 and r < rows and c >= 0 and c < cols.
  • Mark visited when enqueuing. You may change the grid ('1' to '0') only if the interviewer allows it; otherwise keep a visited array, or a set keyed by r * cols + c (a pair needs a custom hash in a C++ unordered_set).
  • Multi-source BFS: put all sources in the queue at time 0 (rotting oranges, distance to the nearest exit).
  • Recursive DFS on a 1000 x 1000 grid is a million calls deep in the worst case: it fails in Python (about 1000 calls by default) and can overflow the stack in Java and C++. Use an explicit queue or stack.
  • Flood fill: if the new colour equals the old colour, return early, or you loop forever.

The red pen

Common traps: mistake → fix

  • Mistake: Recursion is fine for grids

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

  • Mistake: Mark visited when you pop

    Fix: the same cell is queued many times.

  • Mistake: Flood fill with the same colour just does nothing

    Fix: without the early return it loops forever.

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