LeetCode题解 | [简单-数组] 661. 图片平滑器

661. 图片平滑器

题目

包含整数的二维矩阵 M 表示一个图片的灰度。你需要设计一个平滑器来让每一个单元的灰度成为平均灰度 (向下舍入) ,平均灰度的计算是周围的8个单元和它本身的值求平均,如果周围的单元格不足八个,则尽可能多的利用它们。

示例 1:

输入:
[[1,1,1],
 [1,0,1],
 [1,1,1]]
输出:
[[0, 0, 0],
 [0, 0, 0],
 [0, 0, 0]]
解释:
对于点 (0,0), (0,2), (2,0), (2,2): 平均(3/4) = 平均(0.75) = 0
对于点 (0,1), (1,0), (1,2), (2,1): 平均(5/6) = 平均(0.83333333) = 0
对于点 (1,1): 平均(8/9) = 平均(0.88888889) = 0

注意:

给定矩阵中的整数范围为 [0, 255]。
矩阵的长和宽的范围均为 [1, 150]。

思路

直接遍历矩阵暴力解决。

代码

/*
2021/2/2
*/
class Solution {
public:
    vector<vector<int>> imageSmoother(vector<vector<int>>& M) {
        const int length = M[0].size();
        const int width = M.size();
        vector<vector<int>> out;
        
        for (int i = 0; i < width; i++) {
            vector<int> v;
            out.push_back(v);
            for (int j = 0; j < length; j++) {
                int sum  = 0;
                sum += M[i][j];
                sum += (i - 1 >= 0) ? M[i-1][j] : 0;    //上
                sum += (i + 1 < width)  ? M[i+1][j] : 0;     //下
                sum += (j - 1 >= 0) ? M[i][j-1] : 0;    //左
                sum += (j + 1 < length)  ? M[i][j+1] : 0;     //右
                sum += (i - 1 >= 0 && j - 1 >= 0) ? M[i-1][j-1] : 0;   //左上
                sum += (i - 1 >= 0 && j + 1 < length)  ? M[i-1][j+1] : 0;
                sum += (i + 1 < width && j - 1 >= 0)  ? M[i+1][j-1] : 0;
                sum += (i + 1 < width && j + 1 < length)   ? M[i+1][j+1] : 0;

                int cnt = 1;
                cnt += (i - 1 >= 0) ? 1 : 0;    //上
                cnt += (i + 1 < width)  ? 1 : 0;     //下
                cnt += (j - 1 >= 0) ? 1 : 0;    //左
                cnt += (j + 1 < length)  ? 1 : 0;     //右
                cnt += (i - 1 >= 0 && j - 1 >= 0) ? 1 : 0;   //左上
                cnt += (i - 1 >= 0 && j + 1 < length)  ? 1 : 0;
                cnt += (i + 1 < width && j - 1 >= 0)  ? 1 : 0;
                cnt += (i + 1 < width && j + 1 < length)   ? 1 : 0;

                out[i].push_back(sum / cnt);
            }
        }

        return out;
    }
};
原文地址:https://www.cnblogs.com/DylanLiuH2O/p/14398065.html