Find the number of distinct islands in a 2D matrix in Python

PythonServer Side ProgrammingProgramming

Suppose we have a binary matrix. We have to count the number of islands in it. An island is place that is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. We can assume that all four edges of the grid are all surrounded by water.

Suppose the grid is like −

11000
11000
00100
00011

There are three islands.

To solve this, we will follow these steps −

  • There will be two methods, one will be used to count number of islands called numIslands() and makeWater(). The makeWater() will be like −

  • if number of rows in the grid is 0, then return 0

  • n = row count and m := column count, and ans := 0

  • for i in range 0 to n – 1

    • for j in range 0 to m

      • if grid[i, j] = 1, then ans := ans + 1

      • makeWater(i, j, n, m, grid)

  • the makeWater() will take the indices i, j, row and col count n and m, and grid

  • if i <0 or j < 0 or i >= n or j >= m, then return from this method

  • if grid[i, j] = 0, then return otherwise make grid[i, j] := 0

  • call makeWater(i + 1, j, n, m, grid)

  • call makeWater(i, j + 1, n, m, grid)

Example

Let us see the following implementation to get better understanding −

class Solution(object):
   def numIslands(self, grid):
      """
      :type grid: List[List[str]]
      :rtype: int
      """
      if len(grid) == 0:
         return 0
      n= len(grid)
      m = len(grid[0])
      ans = 0
      for i in range(n):
         for j in range(m):
            if grid[i][j] == "1":
               ans+=1
            self.make_water(i,j,n,m,grid)
         return ans
   def make_water(self,i,j,n,m,grid):
      if i<0 or j<0 or i>=n or j>=m:
         return
      if grid[i][j] == "0":
         return
      else:
         grid[i][j]="0"
      self.make_water(i+1,j,n,m,grid)
      self.make_water(i,j+1,n,m,grid)
      self.make_water(i-1,j,n,m,grid)
      self.make_water(i,j-1,n,m,grid)

Input

[["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]]

Output

3
raja
Published on 27-Aug-2020 06:12:59
Advertisements