[LeetCode]661. Image Smoother 解题报告(C++)
题目描述
Given a 2D integer matrix M representing the gray scale of an image, you need to design a smoother to make the gray scale of each cell becomes the average gray scale (rounding down) of all the 8 surrounding cells and itself. If a cell has less than 8 surrounding cells, then use as many as you can.
Example 1:
Input:
[[1,1,1],
[1,0,1],
[1,1,1]]
Output:
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
Explanation:
For the point (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0
For the point (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0
For the point (1,1): floor(8/9) = floor(0.88888889) = 0
Note:
- The value in the given matrix is in the range of [0, 255].
- The length and width of the given matrix are in the range of [1, 150].
题目大意
- 做一个图片的
3x3
滤波器. - 注意边界情况的处理.
解题思路
方法1:
- 开一个二维的数据来填值.
- 遍历图像, 给(i,j)为中心的3x3的数组求和做平均.
- 这里要注意边界判断. 统计用了多少个有用的像素.然后做平均
代码实现:
class Solution {
public:
vector<vector<int>> imageSmoother(vector<vector<int>>& M) {
int row = M.size();
int col = M[0].size();
vector<vector<int>> result;
result.resize(row);
for (int i = 0; i < row; i++) {
result[i].resize(col);
}
// 优秀啊!这样做方向移动!!!简直优秀!!!
vector<vector<int>> dirs = { {-1,-1},{-1,0},{-1,1},
{0,-1},{0,1},
{1,-1},{1,0},{1,1} };
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
int sum = M[i][j];
int cnt = 1;
for (auto dir : dirs) {
int x = i + dir[0], y = j + dir[1];
if (x < 0 || x >= row || y < 0 || y >= col) {
continue;
}
++cnt;
sum += M[x][y];
}
result[i][j] = sum / cnt;
}
}
return result;
}
};
小结
方向移动:
vector<vector<int>> dirs = { {-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1} };
边界判断:
if (x < 0 || x >= row || y < 0 || y >= col) {continue;}