Count Islands in a GridLoading saved progress…

Count Islands in a Grid

You're handed a map drawn on graph paper. Each square is either land or water, and a chunk of land squares that touch edge-to-edge forms one island. Your job is to count how many separate islands the map contains. This is the classic connected-components problem in disguise — the grid is a graph, each land cell is a node, and two land cells are linked when they sit directly next to each other.

Implement gridCountIslands(grid). The grid is a 2D array of the single-character strings '1' (land) and '0' (water). Return the number of distinct islands, where two land cells belong to the same island only if they are adjacent up, down, left, or right — never on a diagonal.

Signature

function gridCountIslands(grid) {
  // grid: string[][] of '1' (land) and '0' (water)
  // returns: number — count of 4-directionally connected land groups
}

Examples

gridCountIslands([
  ['1', '1', '0', '0', '0'],
  ['1', '1', '0', '0', '0'],
  ['0', '0', '1', '0', '0'],
  ['0', '0', '0', '1', '1'],
]);
// 3
// top-left 2x2 block, the lone cell at (2,2), the bottom-right pair
gridCountIslands([
  ['0', '0', '0'],
  ['0', '0', '0'],
]);
// 0  — all water, no islands

Notes

  • Adjacency is 4-directional only. Cells that touch only at a corner (diagonally) are separate islands. A checkerboard of land cells is many one-cell islands, not one.
  • Cell values are the strings '1' and '0', not the numbers 1 and 0. Compare against the strings.
  • Do not mutate the caller's grid. The grid you receive must look identical after the call returns — track visited cells in your own structure, or work on a copy.
  • An empty grid returns 0. [] and [[]] (rows with no columns) both have zero islands. The grid is rectangular: every row has the same length.
Loading editor…