JAVA - 10 LINES OF CODE - E A S Y


  • 1
    J
    class Solution {
        public int[][] imageSmoother(int[][] M) {
            int[][] ret = new int[M.length][M[0].length];
            for(int i = 0; i < M.length; i++) for(int j = 0; j < M[0].length; j++) smooth(M, ret, i, j);
            return ret;
        }
        
    //use a loop instead of writing out all surrounding indexes...(='D)
        public void smooth(int[][] source, int[][] dest, int row, int col) {
            int count = 0, sum = 0;
            for(int i = row-1; i < row-1+3; i++) {
                for(int j = col-1; j < col-1+3; j++) {
                    if(i < 0 || j < 0 || i > source.length-1 || j > source[0].length-1) continue;
                    count++;
                    sum += source[i][j];
                }
            }
            dest[row][col] = (int)Math.floor(sum/count);
        }
    }
    

Log in to reply
 

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