Skip to content

Commit 62ff5a0

Browse files
authored
Create sum-of-remoteness-of-all-cells.cpp
1 parent 70e5cef commit 62ff5a0

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
// Time: O(n^2)
2+
// Space: O(n^2)
3+
4+
// flood fill, bfs, math
5+
class Solution {
6+
public:
7+
long long sumRemoteness(vector<vector<int>>& grid) {
8+
static const vector<pair<int, int>> DIRECTIONS = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
9+
const auto& bfs = [&](int i, int j) {
10+
int64_t total = grid[i][j];
11+
int cnt = 1;
12+
grid[i][j] = -1;
13+
vector<pair<int64_t, int>> q = {{i, j}};
14+
while (!empty(q)) {
15+
vector<pair<int64_t, int>> new_q;
16+
for (const auto& [i, j] : q) {
17+
for (const auto& [di, dj] : DIRECTIONS) {
18+
int ni = i + di, nj = j + dj;
19+
if (!(0 <= ni && ni < size(grid) &&
20+
0 <= nj && nj < size(grid[0]) &&
21+
grid[ni][nj] != -1)) {
22+
continue;
23+
}
24+
total += grid[ni][nj];
25+
++cnt;
26+
grid[ni][nj] = -1;
27+
new_q.emplace_back(ni, nj);
28+
}
29+
}
30+
q = move(new_q);
31+
}
32+
return pair(total, cnt);
33+
};
34+
35+
vector<pair<int64_t, int>> groups;
36+
for (int i = 0; i < size(grid); ++i) {
37+
for (int j = 0; j < size(grid[0]); ++j) {
38+
if (grid[i][j] == -1) {
39+
continue;
40+
}
41+
groups.emplace_back(bfs(i, j));
42+
}
43+
}
44+
int64_t total = 0;
45+
for (const auto& [t, _] : groups) {
46+
total += t;
47+
}
48+
int64_t result = 0;
49+
for (const auto& [t, c] : groups) {
50+
result += (total - t) * c;
51+
}
52+
return result;
53+
}
54+
};

0 commit comments

Comments
 (0)