Program to count number of islands in a given matrix in Python

PythonServer Side ProgrammingProgramming

Suppose we have a binary matrix, we have to find number of islands in the matrix. Here 1 is for land and 0 is for water, so an island is a group of 1s that are neighboring and whose perimeter is surrounded by water. Here we are considering neighbors can only be horizontal or vertical, not diagonal.

So, if the input is like

10100
00100
01100
00000
11011
11101

then the output will be 4.

To solve this, we will follow these steps −

  • Define a function explore() . This will take row, col, matrix
  • if row and col are not in range of matrix or matrix[row, col] is 0, then
    • return
  • matrix[row, col] := 0
  • explore(row + 1, col, matrix)
  • explore(row - 1, col, matrix)
  • explore(row, col + 1, matrix)
  • explore(row, col - 1, matrix)
  • From the main method, do the following −
  • if matrix is null, then
    • return 0
  • islands := 0
  • for row in range 0 to row count of matrix, do
    • for col in range 0 to column count of matrix, do
      • if matrix[row, col] is same as 1, then
        • islands := islands + 1
        • explore(row, col, matrix)
  • return islands

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def explore(self, row, col, matrix):
   if (
         row < 0 or col < 0 or row > len(matrix) - 1 or col > len (matrix[0]) - 1 or          matrix[row][col] == 0):
         return
      matrix[row][col] = 0
      self.explore(row + 1, col, matrix)
      self.explore(row - 1, col, matrix)
      self.explore(row, col + 1, matrix)
      self.explore(row, col - 1, matrix)
      def solve(self, matrix):
         if not matrix:
            return 0
         islands = 0
         for row in range(len(matrix)):
            for col in range(len(matrix[0])):
               if matrix[row][col] == 1:
                  islands += 1
                  self.explore(row, col, matrix)
         return islands
ob = Solution() matrix = [
   [1, 0, 1, 0, 0],
   [0, 0, 1, 0, 0],
   [0, 1, 1, 0, 0],
   [0, 0, 0, 0, 0],
   [1, 1, 0, 1, 1],
   [1, 1, 1, 0, 1]
]
print(ob.solve(matrix))

Input

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

Output

4
raja
Published on 19-Oct-2020 15:55:22
Advertisements