Count Sub Islands LeetCode solution in C++

1
class Solution {
2
public:
3
bool res;
4
void mark_current_island(vector<vector<int>> &grid1, vector<vector<int>> &grid2, int x, int y,
5
int r, int c) {
6
if (x < 0 || x >= r || y < 0 || y >= c || grid2[x][y] != 1) // Boundary case for matrix
7
return;
8

9
// if there is water on grid1 for the location on B then our current island
10
// can't be counted and so we mark res as false
11
if (grid1[x][y] == 0) {
12
res = false;
13
return;
14
}
15
// Mark current cell as visited
16
grid2[x][y] = 0;
17

18
// Make recursive call in all 4 adjacent directions
19
mark_current_island(grid1, grid2, x + 1, y, r, c); // DOWN
20
mark_current_island(grid1, grid2, x, y + 1, r, c); // RIGHT
21
mark_current_island(grid1, grid2, x - 1, y, r, c); // TOP
22
mark_current_island(grid1, grid2, x, y - 1, r, c); // LEFT
23
}
24
int countSubIslands(vector<vector<int>> &grid1, vector<vector<int>> &grid2) {
25
// For FAST I/O
26
ios_base::sync_with_stdio(false);
27
cin.tie(NULL);
28

29
int rows = grid1.size();
30
if (rows == 0) // Empty grid boundary case
31
return 0;
32
int cols = grid1[0].size();
33

34
// Iterate for all cells of the array
35
int no_of_islands = 0;
36

37
// dfs on grid2
38
for (int i = 0; i < rows; ++i) {
39
for (int j = 0; j < cols; ++j) {
40
if (grid2[i][j] == 1) {
41
res = true;
42
mark_current_island(grid1, grid2, i, j, rows, cols);
43
// if current island of grid2 meets the requirement update the no of
44
// islands
45
if (res) no_of_islands += 1;
46
}
47
}
48
}
49

50
return no_of_islands;
51
}
52
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0