[LeetCode] Count Sub Islands

1905. Count Sub Islands

You are given two m x n binary matrices grid1 and grid2 containing only 0’s (representing water) and 1’s (representing land). An island is a group of 1’s connected 4-directionally (horizontal or vertical). Any cells outside of the grid are considered water cells.

An island in grid2 is considered a sub-island if there is an island in grid1 that contains all the cells that make up this island in grid2.

Return the number of islands in grid2 that are considered sub-islands.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
int floodfill(vector<vector<int>>& g1, vector<vector<int>>& g2, int y, int x) {
int res = 0;
if(0 <= y and y < g1.size() and 0 <= x and x < g1[0].size()) {
if(g1[y][x] and g2[y][x]) {
g1[y][x] = g2[y][x] = 0;
res += 1;
res += floodfill(g1,g2,y+1,x);
res += floodfill(g1,g2,y-1,x);
res += floodfill(g1,g2,y,x+1);
res += floodfill(g1,g2,y,x-1);
} else if(g2[y][x]) res = -250000;
}
return res;
}
public:
int countSubIslands(vector<vector<int>>& grid1, vector<vector<int>>& grid2) {
int res = 0;
int n = grid1.size(), m = grid1[0].size();
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++) {
res += (floodfill(grid1,grid2,i,j) > 0);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/23/PS/LeetCode/count-sub-islands/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.