20 lines java solution


  • 0
    L

    Use a 2D array to store all possible directions.

    class Solution {
        public static int[][]dirs = {{1,0},{0,1},{-1,0},{0,-1},{1,1},{1,-1},{-1,-1},{-1,1}};
        public int[][] imageSmoother(int[][] M) {
            int row = M.length;
            int col = M[0].length;
            int[][] res = new int[row][col];
            for(int i=0; i<row; i++){
                for(int j=0; j<col; j++){
                        int count = 1;
                        int sum = M[i][j];
                        for(int[]dir:dirs){
                            int x = i + dir[0];
                            int y = j + dir[1];
                            if(x>=row || y>=col || x<0 || y<0) continue;
                            count++;
                            sum+=M[x][y];
                        }
                        res[i][j] = (int)Math.floor(sum/count);
                }
            }
            return res;
        }
    }
    

Log in to reply
 

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