C++, concise solution, O(n)


  • 0
    Z
    class Solution {
    public:
        vector<vector<int>> imageSmoother(vector<vector<int>>& M) {
            int m = M.size(), n = M[0].size();
            vector<vector<int>> ans(m, vector<int>(n, 0));
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    int cnt = 0;
                    for (int x = -1; x <= 1; x++) {
                        for (int y = -1; y <= 1; y++) {
                            if (i+x >= 0 && i+x < m && j+y >=0 && j+y < n) {
                                cnt++;
                                ans[i][j] += M[i+x][j+y];
                            }
                        }
                    } 
                    ans[i][j] /= cnt;
                }
            }
            return ans;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.