forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
image-smoother.cpp
35 lines (33 loc) · 1.16 KB
/
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
35
// 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();
static const vector<pair<int, int>> directions = { {-1, -1}, {0, -1}, {1, -1},
{-1, 0}, {0, 0}, {1, 0},
{-1, 1}, {0, 1}, {1, 1} };
double total = 0.0;
int count = 0;
for (const auto& direction : directions) {
const auto& ii = i + direction.first;
const auto& jj = j + direction.second;
if (0 <= ii && ii < m && 0 <= jj && jj < n) {
total += M[ii][jj];
++count;
}
}
return static_cast<int>(total / count);
}
};