
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Remove All Islands Surrounded by Water in Python
Suppose we have a binary matrix where 1 represents land and 0 represents water. And an island is a group of 1's that are surrounded by 0s (water) or by the edges. We have to find all of the islands that are completely surrounded by water and modify them into 0s. As we know an island is completed surrounded by water if all of the neighbors (horizontal and vertical not diagonal) are 0s (none of the neighbors are edges).
So, if the input is like
1 | 0 | 0 | 0 |
0 | 1 | 1 | 0 |
0 | 1 | 1 | 0 |
0 | 1 | 1 | 0 |
0 | 0 | 0 | 1 |
then the output will be
1 | 0 | 0 | 0 |
0 | 0 | 0 | 0 |
0 | 0 | 0 | 0 |
0 | 0 | 0 | 0 |
0 | 0 | 0 | 1 |
To solve this, we will follow these steps −
row := row count of A
col := column count of A
B := a matrix of size A and fill with 0
seen := a new set
-
for i in range 0 to row, do
-
for j in range 0 to col, do
-
if i and j are not in range of matrix, then
go for next iteration
-
if (i, j) is seen, then
go for next iteration
-
if A[i, j] is same as 0, then
go for next iteration
d := a double ended queue with one element (i, j)
-
while d is not empry, do
(x, y) := left element of d, and delete from d
B[x, y] := 1
-
for each neighbor (x2, y2) of (x, y), do
-
if (x2, y2) is not seen, then
insert (x2, y2) at the end of d
mark (x2, y2) as seen
-
-
-
return B
Example
Let us see the following implementation to get a better understanding −
from collections import deque class Solution: def solve(self, A): row = len(A) col = len(A[0]) B = [[0 for _ in range(col)] for _ in range(row)] seen = set() def nei(i, j): if i + 1 < row and A[i + 1][j]: yield (i + 1, j) if j + 1 < col and A[i][j + 1]: yield (i, j + 1) if i - 1 >= 0 and A[i - 1][j]: yield (i - 1, j) if j - 1 >= 0 and A[i][j - 1]: yield (i, j - 1) for i in range(row): for j in range(col): if i not in (0, row - 1) and j not in (0, col - 1): continue if (i, j) in seen: continue if A[i][j] == 0: continue d = deque([(i, j)]) while d: x, y = d.popleft() B[x][y] = 1 for x2, y2 in nei(x, y): if (x2, y2) not in seen: d.append((x2, y2)) seen.add((x2, y2)) return B ob = Solution() matrix = [ [1, 0, 0, 0], [0, 1, 1, 0], [0, 1, 1, 0], [0, 1, 1, 0], [0, 0, 0, 1], ] print(ob.solve(matrix))
Input
[ [1, 0, 0, 0], [0, 1, 1, 0], [0, 1, 1, 0], [0, 1, 1, 0], [0, 0, 0, 1], ]
Output
[ [1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 1] ]