Suppose we have a binary matrix where 1 represents land and 0 represents water. And an island is a group of 1s that are surrounded by water. We have to find the size of the largest island. We are allowed to change at most one water cell to land cell.
So, if the input is like
1 | 0 | 1 |
0 | 0 | 0 |
1 | 1 | 0 |
1 | 1 | 1 |
then the output will be 7, as we can turn one water cells to land to connect the two islands. So final matrix is like −
1 | 0 | 1 |
0 | 0 | 0 |
1 | 1 | 0 |
1 | 1 | 1 |
To solve this, we will follow these steps −
R := row count of mat, C := column count of mat
mass := a new map
id := 555
Define a function floodfill() . This will take r, c, id
if r and c are in range of matrix and mat[r, c] is 1, then
mat[r, c] := id
mass[id] := mass[id] + 1
for each pair (r2, c2) in [(r + 1, c) ,(r − 1, c) ,(r, c + 1) ,(r, c − 1) ], do
floodfill(r2, c2, id)
From the main method do the following −
for r in range 0 to R, do
for c in range 0 to C, do
if mat[r, c] is same as 1, then
id := id + 1
mass[id] := 0
floodfill(r, c, id)
ans := maximum of (all values of mass and 1)
for r in range 0 to R − 1, do
for c in range 0 to C − 1, do
if mat[r, c] is not same as 0, then
go for next iteration
island_set := a new set
for each pair (r2, c2) in [(r + 1, c) ,(r − 1, c) ,(r, c + 1) ,(r, c − 1) ], do
if r2 and c2 are in range of mat and mat[r2, c2] is 1, then
add mat[r2, c2] into island_set
ans := maximum of ans and (1 + sum of all mass[island] for each island in island_set)
return ans
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, mat): R, C = len(mat), len(mat[0]) mass = {} id = 555 def floodfill(r, c, id): nonlocal R, C, mat, mass if 0 <= r < R and 0 <= c < C and mat[r][c] == 1: mat[r][c] = id mass[id] += 1 for r2, c2 in [(r + 1, c), (r − 1, c), (r, c + 1), (r, c − 1)]: floodfill(r2, c2, id) for r in range(R): for c in range(C): if mat[r][c] == 1: id += 1 mass[id] = 0 floodfill(r, c, id) ans = max([val for val in mass.values()] + [1]) for r in range(R): for c in range(C): if mat[r][c] != 0: continue island_set = set() for r2, c2 in [(r + 1, c), (r − 1, c), (r, c + 1),(r, c − 1)]: if 0 <= r2 < R and 0 <= c2 < C and mat[r2][c2]: island_set.add(mat[r2][c2]) ans = max(ans, 1 + sum([mass[island] for island in island_set])) return ans ob = Solution() matrix = [ [1, 0, 1], [0, 0, 0], [1, 1, 0], [1, 1, 1] ] print(ob.solve(matrix))
Input
[ [1, 0, 1], [0, 0, 0], [1, 1, 0], [1, 1, 1] ]
Output
7