-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
sum-of-remoteness-of-all-cells.cpp
54 lines (52 loc) · 1.75 KB
/
sum-of-remoteness-of-all-cells.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Time: O(n^2)
// Space: O(n^2)
// flood fill, bfs, math
class Solution {
public:
long long sumRemoteness(vector<vector<int>>& grid) {
static const vector<pair<int, int>> DIRECTIONS = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
const auto& bfs = [&](int i, int j) {
int64_t total = grid[i][j];
int cnt = 1;
grid[i][j] = -1;
vector<pair<int64_t, int>> q = {{i, j}};
while (!empty(q)) {
vector<pair<int64_t, int>> new_q;
for (const auto& [i, j] : q) {
for (const auto& [di, dj] : DIRECTIONS) {
int ni = i + di, nj = j + dj;
if (!(0 <= ni && ni < size(grid) &&
0 <= nj && nj < size(grid[0]) &&
grid[ni][nj] != -1)) {
continue;
}
total += grid[ni][nj];
++cnt;
grid[ni][nj] = -1;
new_q.emplace_back(ni, nj);
}
}
q = move(new_q);
}
return pair(total, cnt);
};
vector<pair<int64_t, int>> groups;
for (int i = 0; i < size(grid); ++i) {
for (int j = 0; j < size(grid[0]); ++j) {
if (grid[i][j] == -1) {
continue;
}
groups.emplace_back(bfs(i, j));
}
}
int64_t total = 0;
for (const auto& [t, _] : groups) {
total += t;
}
int64_t result = 0;
for (const auto& [t, c] : groups) {
result += (total - t) * c;
}
return result;
}
};