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.
function gridCountIslands(grid) {
// grid: string[][] of '1' (land) and '0' (water)
// returns: number — count of 4-directionally connected land groups
}
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
'1' and '0', not the numbers 1 and 0. Compare against the strings.0. [] and [[]] (rows with no columns) both have zero islands. The grid is rectangular: every row has the same length.