← Whiteboard questions

Count the islands in a grid

DSA, Medium

Which structure or algorithm, and what does it cost.

You get a grid of the characters "1" (land) and "0" (water). Two land cells are connected if they share an edge (up, down, left or right). Diagonal cells are not connected. An island is a group of connected land cells. Return the number of islands. An empty grid has 0 islands.

Examples

Input 11000 11000 00100 00011
Output 3
Why top-left block, the single cell in the middle, the bottom-right pair
Input 10 01
Output 2
Why the two 1s touch only on a corner, so they are separate islands
Input 000
Output 0
Why no land

Constraints

Your answer must contain

Count the islands in a grid · OpsKarma interview practice