Number of islands
Count connected land areas on a map made of a character grid. Graph search (BFS/DFS) over cells – and the trap of deep recursion on a large map.
A drone map is a grid of cells: '1' is land, '0' is water. An island is a maximal land area in which every cell can reach every other one by moving up, down, left and right (diagonals do not count). How many islands are on the map?
Task
The function gets the grid as a list of equally long strings (each string is a row) and returns the number of islands. The input must not be modified (strings are immutable anyway – you need your own visited array).
Signatures: countIslands(grid) (JS/TS), count_islands(grid) (Python), Solution.CountIslands (C#, string[]), Solution.countIslands (Java, String[]), CountIslands (Go, []string).
Examples
| Grid | Result |
|---|---|
["11110", "11010", "11000", "00000"] | 1 |
["11000", "11000", "00100", "00011"] | 3 |
["101", "010", "101"] | 5 – diagonals do not connect |
["11111", "10001", "10101", "10001", "11111"] | 2 – a ring and an islet inside |
[] | 0 |
Constraints
0 ≤ rows, columns ≤ 300(up to 90,000 cells).- One island may cover the whole map – a recursive DFS then goes tens of thousands of calls deep.
Expected complexity
O(R · C) time, O(R · C) memory for the visited array and the queue/stack.