Skip to content

Commit 67abafe

Browse files
committed
Time: 2756 ms (5.07%), Space: 118.6 MB (26.09%) - LeetHub
1 parent 64b2871 commit 67abafe

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
class Solution {
2+
public:
3+
int countSubIslands(vector<vector<int>>& grid1, vector<vector<int>>& grid2) {
4+
5+
int n = grid1.size();
6+
int m = grid1[0].size();
7+
8+
vector<vector<bool>> visited(n, vector<bool>(m, false)), visited2(n, vector<bool>(m, false));
9+
10+
function<void(int, int)> dfs = [&](int i, int j)
11+
{
12+
if(i < 0 or j < 0 or i >= n or j >= m or visited[i][j] or !grid1[i][j])
13+
return;
14+
15+
visited[i][j] = 1;
16+
17+
dfs(i-1, j);
18+
dfs(i, j+1);
19+
dfs(i+1, j);
20+
dfs(i, j-1);
21+
};
22+
23+
for(int i = 0; i < n; ++i)
24+
{
25+
for(int j = 0; j < m; ++j)
26+
{
27+
if(!visited[i][j] and grid1[i][j])
28+
dfs(i, j);
29+
}
30+
}
31+
32+
function<bool(int, int)> dfs2 = [&](int i, int j) -> bool{
33+
if(i < 0 or j < 0 or i >= n or j >= m or visited2[i][j] or !grid2[i][j])
34+
return true;
35+
36+
if(!visited[i][j]) return false;
37+
38+
visited2[i][j] = true;
39+
40+
bool up, left, right, down;
41+
up = left = right = down = true;
42+
43+
up = dfs2(i-1, j);
44+
left = dfs2(i, j-1);
45+
down = dfs2(i+1, j);
46+
right = dfs2(i, j+1);
47+
48+
return up and left and down and right;
49+
};
50+
51+
int subIsland = 0;
52+
53+
for(int i = 0; i < n; ++i)
54+
{
55+
for(int j = 0; j < m; ++j)
56+
{
57+
if(!visited2[i][j] and grid2[i][j])
58+
{
59+
if(dfs2(i, j))
60+
{
61+
++subIsland;
62+
}
63+
}
64+
}
65+
}
66+
67+
return subIsland;
68+
}
69+
};

0 commit comments

Comments
 (0)