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.

class Solution {
    public int[][] imageSmoother(int[][] M) {
        int m = M.length;
        int n = M[0].length;
        int[][] res = new int[m][n];
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                res[i][j] = getVal(M, i, j);
            }
        }

        return res;
    }

    public int getVal(int[][] M, int i, int j) {
        int sum = M[i][j];
        int count = 1;

        int m = M.length;
        int n = M[0].length;
        if(i - 1 >= 0) {
            sum += M[i - 1][j];
            count++;

            if(j - 1 >= 0) {
                sum += M[i - 1][j - 1];
                count++;
            }
            if(j + 1 < n) {
                sum += M[i - 1][j + 1];
                count++;
            }
        }
        if(i + 1 < m) {
            sum += M[i + 1][j];
            count++;

            if(j - 1 >= 0) {
                sum += M[i + 1][j - 1];
                count++;
            }
            if(j + 1 < n) {
                sum += M[i + 1][j + 1];
                count++;
            }
        }
        if(j - 1 >= 0) {
            sum += M[i][j - 1];
            count++;
        }
        if(j + 1 < n) {
            sum += M[i][j + 1];
            count++;
        }

        return sum / count;
    }
}

results matching ""

    No results matching ""