-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcount-sub-islands.cpp
37 lines (33 loc) · 1.19 KB
/
count-sub-islands.cpp
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
27
28
29
30
31
32
33
34
35
36
37
class Solution {
public:
int countSubIslands(vector<vector<int>>& grid1, vector<vector<int>>& grid2) {
int count = 0;
bool found = true;
vector<pair<int, int>> directions = { {0, 1}, {0, -1}, {-1, 0}, {1, 0} };
function<void (int, int)> traverseMark = [&] (int x, int y) {
if (grid1[x][y] != grid2[x][y]) {
found = false;
return;
}
grid2[x][y] = 0;
for (auto direction: directions) {
int nx = x + direction.first;
int ny = y + direction.second;
if (nx < 0
|| ny < 0
|| nx >= grid2.size()
|| ny >= grid2[0].size()
|| !grid2[nx][ny]) continue;
traverseMark(nx, ny);
}
};
for(int i = 0; i < grid2.size(); i++)
for(int j = 0; j < grid2[i].size(); j++)
if (grid1[i][j] == grid2[i][j] && grid2[i][j]) {
found = true;
traverseMark(i, j);
if (found) count++;
}
return count;
}
};