Skip to content
DSA in JavaScript
← All patterns

Matrix Traversal

0/18 solved

What it is

Treat a grid as a graph where each cell connects to its neighbours, and walk it with loops, DFS or BFS.

Used for

Islands, flood fill, spiral order, rotating or searching a 2D grid.
00000001000111000100

islands = 0

Step 1 of 6

Goal: count the islands of 1s in this grid (0 is water). Treat the grid as a map where each cell touches its neighbours above, below, left and right. Scan the cells one by one.

You see

  • 2D grid of cells
  • Islands, regions, flood fill
  • Spiral, diagonal or rotation walks

Learn it in

2D Arrays (Matrices)Unique Paths ProblemSquare Matrix In-Place RotationMatrices

Template

function islands(grid) {  let count = 0;  const sink = (r, c) => {    if (grid[r]?.[c] !== '1') return;    grid[r][c] = '0';    sink(r + 1, c); sink(r - 1, c); sink(r, c + 1); sink(r, c - 1);  };  grid.forEach((row, r) => row.forEach((v, c) => { if (v === '1') { count++; sink(r, c); } }));  return count;}

Practice problems