-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathcount-islands-with-total-value-divisible-by-k.cpp
More file actions
45 lines (42 loc) · 1.41 KB
/
count-islands-with-total-value-divisible-by-k.cpp
File metadata and controls
45 lines (42 loc) · 1.41 KB
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
38
39
40
41
42
43
44
45
// Time: O(m * n)
// Space: O(m + n)
// bfs, flood fill
class Solution {
public:
int countIslands(vector<vector<int>>& grid, int k) {
static const vector<pair<int, int>> DIRECTIONS = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
const auto& bfs = [&](int i, int j) {
if (!grid[i][j]) {
return false;
}
int total = grid[i][j] % k;
grid[i][j] = 0;
vector<pair<int, int>> q = {{i, j}};
while (!empty(q)) {
vector<pair<int, int>> new_q;
for (const auto& [i, j] : q) {
for (const auto& [di, dj] : DIRECTIONS) {
const int ni = i + di, nj = j + dj;
if (!(0 <= ni && ni < size(grid) && 0 <= nj && nj < size(grid[0]) && grid[ni][nj])) {
continue;
}
total = (total + grid[ni][nj]) % k;
grid[ni][nj] = 0;
new_q.emplace_back(ni, nj);
}
}
q = move(new_q);
}
return total == 0;
};
int result = 0;
for (int i = 0; i < size(grid); ++i) {
for (int j = 0; j < size(grid[0]); ++j) {
if (bfs(i, j)) {
++result;
}
}
}
return result;
}
};