Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Program to count number of overlapping islands in two maps in Python
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
- mark(i, j + 1)
- for j in range 0 to c - 1, do
- if mat1[i, j] is not same as mat2[i, j], then
- mark(i, j)
- if mat1[i, j] is not same as mat2[i, j], then
- for j in range 0 to c - 1, do
- if mat1[i, j] is non-zero, then
- islands := islands + 1
- mark(i, j)
- if mat1[i, j] is non-zero, then
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 jInput
[ [1, 0, 1], [1, 0, 0], [1, 0, 1] ] [ [1, 0, 1], [1, 0, 0], [1, 0, 0] ]Output
2
Advertisements
