100 XP

94. Count the islands

Advanced graphs grids

A map is a grid of cells: 1 for land, 0 for water. An island is a group of land cells joined up, down, left or right; land cells that only touch at a corner belong to different islands. The water around the edge of the map is not shown, so land on the edge is still part of an island.

Write a function count_islands(grid) that takes the map as a list of rows and returns how many islands it has.

  • An island can be any shape, winding around, with water inside it.
  • A map with no land has 0 islands.

When you find a land cell you haven't seen, it starts a new island: then visit every land cell joined to it, so that none of that island is counted again.

Example 1

Inputgrid = [[1, 1, 0], [0, 1, 0], [0, 0, 1]]
Output2
ExplanationThree joined cells, and the lone corner.

Example 2

Inputgrid = [[1, 0, 1], [0, 1, 0], [1, 0, 1]]
Output5
ExplanationCorners touching don't join islands.

Example 3

Inputgrid = [[1, 0, 1], [1, 0, 1], [1, 1, 1]]
Output1
ExplanationBoth arms are joined along the bottom.

Constraints

  • grid has 1 to 20 rows of 1 to 20 cells each, all rows the same length; every cell is 0 or 1.

Submit also runs 8 more tests you can't see.

Code
def count_islands(grid):
    """Count the islands of land on the map.

    grid: list of rows of 1 (land) and 0 (water)
    Returns: int, how many groups of land cells are
        joined up, down, left or right
    """
    # Write your code here
    pass