Skip to contentKEEP THE CRAFTTHE SANCTUARY

Number of Islands

Count the islands of land cells joined up, down, left or right.

The problem

Implement Solution.numIslands(grid). grid is a list of rows, and each cell is the string '1' (land) or '0' (water). An island is a group of land cells joined up, down, left or right; diagonal neighbours are not joined. Return the number of islands as an int. The grid has 1 to 300 rows and 1 to 300 columns. If the grid is empty, return 0.

Starter code

class Solution:
    def numIslands(self, grid):
        pass

Public examples

  1. grid = [["1", "1", "0", "0"], ["1", "0", "0", "1"], ["0", "0", "1", "1"]]gives2
  2. grid = [["1", "0", "1"]]gives2
  3. grid = [["0", "0", "1"], ["0", "1", "1"]]gives1

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.