data-structures · intermediate · ~15 min

Count islands (flood fill)

Flood fill on a grid.

Challenge

A rows×cols grid (row-major, 0/1). A island is a maximal group of 1s joined up/down/left/right.

int count_islands(const int *grid,int rows,int cols);

Return the number of islands.

Input format

grid rows·cols of 0/1.

Output format

Island count.

Constraints

4-directional connectivity (no diagonals).

Starter code

#include <stddef.h>
/* Number of connected regions of 1s (4-directional) in a rows x cols grid (row-major, 0/1). */
int count_islands(const int *grid,int rows,int cols){ (void)grid;(void)rows;(void)cols; return 0; }

Common mistakes

Counting diagonal neighbors as connected; mutating the caller's grid (work on a copy).

Edge cases to handle

All 0 → 0; all 1 → 1.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.