Easy to understand Java solution with two private method


  • 0
    Q

    The value method is the return the value of a cell, if exsits returns value, else return 0.
    The count method is the count the number of valid cell, if exsits returns 1, else return 0.

    class Solution {
        public int[][] imageSmoother(int[][] M) {
            if (M.length==0 || M[0].length==0) return M;
            int [][] m = new int [M.length][M[0].length];
            for (int i=0;i<M.length;i++){
                for (int j=0;j<M[0].length;j++){
                    m[i][j]=(value(M,i-1,j-1)+value(M,i-1,j)+value(M,i-1,j+1)+value(M,i,j-1)+value(M,i,j)+value(M,i,j+1)+value(M,i+1,j-1)+value(M,i+1,j)+value(M,i+1,j+1))/(count(M,i-1,j-1)+count(M,i-1,j)+count(M,i-1,j+1)+count(M,i,j-1)+count(M,i,j)+count(M,i,j+1)+count(M,i+1,j-1)+count(M,i+1,j)+count(M,i+1,j+1));
                }
            }
            return m;
        }
        private int value(int[][] M,int i,int j){
            if (i<0 || i>=M.length || j<0 || j>=M[0].length) return 0;
            return M[i][j];        
        }
        private int count(int[][] M,int i,int j){
            if (i<0 || i>=M.length || j<0 || j>=M[0].length) return 0;
            return 1;
        }
    }
    

Log in to reply
 

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