Program to find number of distinct island shapes from a given matrix in Python


Suppose we have a 2d binary matrix, we have to find the number of distinct islands in the given matrix. Here 1 represents land and 0 represents water, so an island is a set of 1s that are close and whose perimeter is surrounded by water. Here two islands are unique if their shapes are different.

So, if the input is like

10000
10101
01101
00100
10000
11011

then the output will be 4 (distinct islands are in different color).

To solve this, we will follow these steps −

  • Define a function dfs() . This will take i, j, k, l

  • mat[i, j] := 0

  • insert pair (i − k, j − l) at the end of shape

  • if i + 1 < row count of mat and mat[i + 1, j] is 1, then

    • dfs(i + 1, j, k, l)

  • if j + 1 < column count of mat and mat[i, j + 1] is 1, then

    • dfs(i, j + 1, k, l)

  • if i − 1 >= 0 and mat[i − 1, j] is 1, then

    • dfs(i − 1, j, k, l)

  • if j − 1 >= 0 and mat[i, j − 1] is 1, then

    • dfs(i, j − 1, k, l)

  • From the main method do the following −

  • cnt := 0

  • shapes := a new set

  • for i in range 0 to row count of mat, do

    • for j in range 0 to column count of mat, do

      • if mat[i, j] is 1, then

        • shape := a new list

        • dfs(i, j, i, j)

        • if shape is not in shapes, then

          • cnt := cnt + 1

        • insert shape into shapes

  • return cnt

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, mat):
      def dfs(i, j, k, l):
         mat[i][j] = 0
         shape.append((i − k, j − l))
      if i + 1 < len(mat) and mat[i + 1][j]:
         dfs(i + 1, j, k, l)
      if j + 1 < len(mat[0]) and mat[i][j + 1]:
         dfs(i, j + 1, k, l)
      if i − 1 >= 0 and mat[i − 1][j]:
         dfs(i − 1, j, k, l)
      if j − 1 >= 0 and mat[i][j − 1]:
         dfs(i, j − 1, k, l)
   cnt = 0
   shapes = set()
      for i in range(len(mat)):
         for j in range(len(mat[0])):
            if mat[i][j]:
               shape = []
               dfs(i, j, i, j)
               shape = tuple(shape)
               if shape not in shapes:
                  cnt += 1
                  shapes.add(shape)
      return cnt
ob = Solution()
matrix = [
   [1, 0, 0, 0, 0],
   [1, 0, 1, 0, 1],
   [0, 1, 1, 0, 1],
   [0, 0, 1, 0, 0],
   [1, 0, 0, 0, 0],
   [1, 1, 0, 1, 1]
]
print(ob.solve(matrix))

Input

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

Output

4

Updated on: 26-Dec-2020

198 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements