Menu
CoddyTech

Number of Islands

MediumGraphspython iconjava iconcpp iconc iconjs icon+10

You get a map as a list of strings of equal length, where '1' is a square of land and '0' is a square of water. Two land squares belong to the same island when they share a side: up, down, left or right. Squares that only meet at a corner are not connected. Return the number of islands.

Function

numIslands(grid: string-array) → integer
gridstring-array
the map, one string per row
Returnsinteger
the number of islands

Constraints

  • 1 ≤ grid.length ≤ 150
  • 1 ≤ grid[i].length ≤ 150
  • Every row has the same length.
  • Every character is '0' or '1'.

Examples

Input
grid = ["11000", "11000", "00100", "00011"]
Output
3
Explanation
The four squares in the top left form one island. The middle square of the third row only touches them at a corner, so it is a second island. The bottom right pair is the third.
challenge icon

Follow-up

Land now appears one square at a time on a map of water. Can you report the number of islands after each new square without scanning the whole map again?

Reset code
def numIslands(grid):
    # Write code here

Test #1

Test #2

Argument

grid = ["11000", "11000", "00100", "00011"]

Expected Output

3