-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
find-the-grid-of-region-average.cpp
59 lines (57 loc) · 1.97 KB
/
find-the-grid-of-region-average.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
55
56
57
58
59
// Time: O(m * n)
// Space: O(m * n)
// array
class Solution {
public:
vector<vector<int>> resultGrid(vector<vector<int>>& image, int threshold) {
const auto& check = [&](int i, int j) {
for (int ni = i - 1; ni <= i; ++ni) {
for (int nj = j - 1; nj <= j + 1; ++nj) {
if (abs(image[ni][nj] - image[ni + 1][nj]) > threshold) {
return false;
}
}
}
for (int ni = i - 1; ni <= i + 1; ++ni) {
for (int nj = j - 1; nj <= j; ++nj) {
if (abs(image[ni][nj] - image[ni][nj + 1]) > threshold) {
return false;
}
}
}
return true;
};
vector<vector<int>> result(size(image), vector<int>(size(image[0])));
vector<vector<int>> cnt(size(image), vector<int>(size(image[0])));
for (int i = 1; i + 1 < size(image); ++i) {
for (int j = 1; j + 1 < size(image[0]); ++j) {
if (!check(i, j)) {
continue;
}
int total = 0;
for (int ni = i - 1; ni <= i + 1; ++ni) {
for (int nj = j - 1; nj <= j + 1; ++nj) {
total += image[ni][nj];
}
}
total /= 9;
for (int ni = i - 1; ni <= i + 1; ++ni) {
for (int nj = j - 1; nj <= j + 1; ++nj) {
++cnt[ni][nj];
result[ni][nj] += total;
}
}
}
}
for (int i = 0; i < size(image); ++i) {
for (int j = 0; j < size(image[0]); ++j) {
if (cnt[i][j]) {
result[i][j] /= cnt[i][j];
} else {
result[i][j] = image[i][j];
}
}
}
return result;
}
};