Program to find number of islands, from where we cannot leave in Python


Suppose we have a binary matrix. Here 1 represents land and 0 represents water. From any land we can move up, down, left or right but not diagonally to another land cell or go off the matrix. We have to find the number of land cells from which we cannot go off the matrix.

So, if the input is like

0001
0110
0110
0001

then the output will be 4, as There's 4 land squares in the middle from which we cannot walk off the matrix.

To solve this, we will follow these steps −

  • q := a list of pairs (i, j) for each row i and column when matrix[i, j] is land i and j are border indices
  • idx := 0
  • for each pair (x, y) in q, do
    • matrix[x, y] := 0
  • while idx < size of q, do
    • x, y := q[idx]
    • for each (dx, dy) in [(-1, 0) ,(0, -1) ,(0, 1) ,(1, 0) ], do
      • nx := x + dx
      • ny := y + dy
      • if 0 <= nx < row count of matrix and 0 <= ny < column count of matrix[nx] and matrix[nx, ny] is 1, then
        • matrix[nx, ny] := 0
        • insert (nx, ny) at the end of q
    • idx := idx + 1
  • return sum of all elements of matrix

Example

Let us see the following implementation to get better understanding −

def solve(matrix):
   q = [(i, j) for i in range(len(matrix)) for j in range(len(matrix[i])) if matrix[i][j] and (i == 0 or i == len(matrix) - 1 or j == 0 or j == len(matrix[i]) - 1)]
   idx = 0
   for x, y in q:
      matrix[x][y] = 0
   while idx < len(q):
      x, y = q[idx]
      for dx, dy in [(-1, 0), (0, -1), (0, 1), (1, 0)]:
         nx, ny = x + dx, y + dy
         if 0 <= nx < len(matrix) and 0 <= ny < len(matrix[nx]) and matrix[nx][ny]:
            matrix[nx][ny] = 0
            q.append((nx, ny))
      idx += 1
   return sum(sum(row) for row in matrix)

matrix = [
[0, 0, 0, 1],
[0, 1, 1, 0],
[0, 1, 1, 0],
[0, 0, 0, 1]
]
print(solve(matrix))

Input

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

Output

4

Updated on: 18-Oct-2021

118 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements