Skip to content

Commit 50761cc

Browse files
Create 1905-count-sub-islands.cpp
1 parent 2d0e0cc commit 50761cc

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

cpp/1905-count-sub-islands.cpp

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Solution {
2+
public:
3+
int countSubIslands(vector<vector<int>>& grid1, vector<vector<int>>& grid2) {
4+
const int ROWS = grid1.size(), COLS = grid1[0].size();
5+
set<int> visit;
6+
7+
function<bool(int, int)> dfs = [&] (int r, int c) -> bool {
8+
if (
9+
r < 0
10+
|| c < 0
11+
|| r == ROWS
12+
|| c == COLS
13+
|| grid2[r][c] == 0
14+
|| visit.count(r*COLS + c)
15+
)
16+
return true;
17+
18+
visit.insert(r*COLS + c);
19+
bool res = true;
20+
if(grid1[r][c] == 0)
21+
res = false;
22+
23+
res = dfs(r - 1, c) && res;
24+
res = dfs(r + 1, c) && res;
25+
res = dfs(r, c - 1) && res;
26+
res = dfs(r, c + 1) && res;
27+
return res;
28+
};
29+
30+
int count = 0;
31+
for(int r = 0; r < ROWS; r++)
32+
for(int c = 0; c < COLS; c++)
33+
if(grid2[r][c] && !visit.count(r*COLS + c) && dfs(r, c))
34+
count += 1;
35+
return count;
36+
}
37+
};

0 commit comments

Comments
 (0)