# Program to count number of overlapping islands in two maps in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose we have two binary matrices mat1 and mat2. Here 1 represents land and 0 represents water, if there is a group of 1(land) surrounded by water is called island. We have to find the number of islands that exist in both mat1 and mat2 at the exact same coordinates.

So, if the input is like mat1 =

 1 0 1 1 0 0 1 0 0

And mat2 =

 1 0 1 1 0 0 1 0 1

then the output will be 2, because the overlapping islands are,

 1 0 1 1 0 0 1 0 1

so there are two overlapping islands.

To solve this, we will follow these steps −

• r := row count of mat1
• c := column count of mat1
• last_row := r - 1
• last_col := c - 1
• Define a function mark() . This will take i, j
• mat1[i, j] := 0
• mat2[i, j] := 0
• if i is non zero and (mat1[i - 1, j] or mat2[i - 1, j] any one is non zero), then
• mark(i - 1, j)
• if j is non zero and (mat1[i, j - 1] or mat2[i, j - 1] any one is non zero), then
• mark(i, j - 1)
• if j < last_col and (mat1[i, j + 1] or mat2[i, j + 1] any one is non zero), then
• mark(i, j + 1)
• if i < last_row and (mat1[i + 1, j] or mat2[i + 1, j] any one is non zero), then
• mark(i + 1, j)
• From the main method, do the following −
• for i in range 0 to r - 1, do
• for j in range 0 to c - 1, do
• if mat1[i, j] is not same as mat2[i, j], then
• mark(i, j)
• islands := 0
• for i in range 0 to r - 1, do
• for j in range 0 to c - 1, do
• if mat1[i, j] is non-zero, then
• islands := islands + 1
• mark(i, j)
• return islands

## Example

Let us see the following implementation to get better understanding −

def solve(mat1, mat2):
r = len(mat1)
c = len(mat1[0])
last_row = r - 1
last_col = c - 1

def mark(i, j):
mat1[i][j] = mat2[i][j] = 0
if i and (mat1[i - 1][j] or mat2[i - 1][j]):
mark(i - 1, j)
if j and (mat1[i][j - 1] or mat2[i][j - 1]):
mark(i, j - 1)
if j < last_col and (mat1[i][j + 1] or mat2[i][j + 1]):
mark(i, j + 1)
if i < last_row and (mat1[i + 1][j] or mat2[i + 1][j]):
mark(i + 1, j)

for i in range(r):
for j in range(c):
if mat1[i][j] != mat2[i][j]:
mark(i, j)

islands = 0
for i in range(r):
for j in range(c):
if mat1[i][j]:
islands += 1
mark(i, j)
return islands

mat1 = [
[1, 0, 1],
[1, 0, 0],
[1, 0, 1]
]
mat2 = [
[1, 0, 1],
[1, 0, 0],
[1, 0, 0]
]
print(solve(mat1, mat2))

## Input

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

## Output

2
Updated on 18-Oct-2021 13:26:26