forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
image-smoother.cpp
34 lines (32 loc) · 964 Bytes
/
image-smoother.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
// Time: O(m * n)
// Space: O(1)
class Solution {
public:
vector<vector<int>> imageSmoother(vector<vector<int>>& M) {
const auto& m = M.size(), &n = M[0].size();
vector<vector<int>> result(M);
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
result[i][j] = getGray(M, i, j);
}
}
return result;
}
private:
int getGray(const vector<vector<int>>& M, int i, int j) {
const auto& m = M.size(), &n = M[0].size();
double total = 0.0;
int count = 0;
for (int r = -1; r < 2; ++r) {
for (int c = -1; c < 2; ++c) {
const auto& ii = i + r;
const auto& jj = j + c;
if (0 <= ii && ii < m && 0 <= jj && jj < n) {
total += M[ii][jj];
++count;
}
}
}
return static_cast<int>(total / count);
}
};