Count the islands in a grid
Coding problemMediumAsked in: Amazon, Apple, Google, Meta, Microsoft, Uber
You are given a map as a grid of characters, one string per row: 1 is land and 0 is water. An island is a group of land cells joined up, down, left or right (not diagonally). Return the number of islands.
Everything outside the grid is water.
Examples
Example 1
Input: grid = ["11110","11010","11000","00000"]
Output: 1
Example 2
Input: grid = ["11000","11000","00100","00011"]
Output: 3
Example 3
Input: grid = ["10","01"]
Output: 2
Cells that touch only at a corner are not joined.
Constraints
- The grid has between 1 and 300 rows and between 1 and 300 columns; all rows have the same length
- Every cell is 0 or 1
Run checks the 3 examples. Submit also runs the hidden tests: edge cases, large inputs and a time limit.
Run your code to see the results here. Ctrl or Cmd + Enter runs; add Shift to submit.