【Leetcode_easy】661. Image Smoother

problem

661. Image Smoother

题意:其实类似于图像处理的均值滤波。

solution:

妙处在于使用了一个dirs变量来计算邻域数值,看起来更简洁!

class Solution {
public:
    vector<vector<int>> imageSmoother(vector<vector<int>>& M) {
        if(M.empty() || M[0].empty()) return {};
        vector<vector<int>> res = M, dirs = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, 
                                             {0, 1}, {1, -1}, {1, 0}, {1, 1} };//dirs err.
        int m = M.size(), n = M[0].size();
        for(int i=0; i<m; i++)
        {
            for(int j=0; j<n; j++)
            {
                int sum = M[i][j], num = 1;//err.
                for(auto dir : dirs)
                {
                    int x = i+dir[0], y = j+dir[1];
                    if(x<0 || x>=m || y<0 || y>=n) continue;//err.
                    num++;
                    sum += M[x][y];
                }
                res[i][j] = sum / num;
            }
            
        }
        return res;
        
    }
};

参考

1. Leetcode_easy_661. Image Smoother;

原文地址:https://www.cnblogs.com/happyamyhope/p/11091131.html