leetcode 661. 图片平滑器(Image Smoother)

Posted zhanzq

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 661. 图片平滑器(Image Smoother)相关的知识,希望对你有一定的参考价值。

题目描述:

包含整数的二维矩阵 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

注意:

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

解法:

class Solution {
public:
    
    bool valid(int i, int j, int m, int n){
        return i >= 0 && j >= 0 && i < m && j < n;
    }
    
    vector<vector<int>> imageSmoother(vector<vector<int>>& M) {
        vector<vector<int>> res = M;
        int m = M.size();
        int n = M[0].size();
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                int count = 0;
                int sum_val = 0;
                for(int di = -1; di <= 1; di++){
                    for(int dj = -1; dj <= 1; dj++){
                        if(valid(i+di, j+dj, m, n)){
                            count++;
                            sum_val += M[i+di][j+dj];
                        }
                    }
                }
                res[i][j] = sum_val/count;
            }
        }
        return res;
    }
};

以上是关于leetcode 661. 图片平滑器(Image Smoother)的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode661图片平滑器

LeetCode 661. Image Smoother (图像平滑)

[LeetCode] Image Smoother 图片平滑器

LeetCode 002 数组系列

[leetcode-661-Image Smoother]

[LeetCode] 661. Image Smoother_Easy