Clean and easy Java solution


  • 0
    T
    public int[][] imageSmoother(int[][] M) {
        if(M == null || M.length == 0) return M;
        int row = M.length;
        int col = M[0].length;
        
        int[][] result = new int[row][col];
        
        for(int i = 0; i < row; i++) {
            for(int j = 0; j < col; j++){
                result[i][j] = getGrayScale(M, i, j);
            }
        }
        
        return result;
    }
    
    private int getGrayScale(int[][] M, int i, int j){                
        int[] dx = {-1,0,1};
        int[] dy = {-1,0,1};
        
        int sum = 0;
        int count = 0;
        
        for(int m = 0; m < 3; m++){
            if(i + dx[m] < 0 || i + dx[m] >= M.length) continue;
            
            for(int n = 0; n < 3; n++){
                
                if(j + dy[n] < 0 || j + dy[n] >= M[0].length) continue;
                
                sum += M[i + dx[m]][j + dy[n]];
                
                count++;
            }
        }
        
        return sum/count;
    }

Log in to reply
 

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