Reasonable Java solution, few lines


  • 0
    H
    class Solution {
        public int[][] imageSmoother(int[][] M) {
            // assume valid input
            int height = M.length;
            int width = M[0].length;
            int[][] result = new int[height][width];
            for(int i = 0; i < height; i++) {
                for(int j = 0; j < width; j++) {
                    double sum = 0.0;
                    int total = 0;
                    for(int x: new int[]{-1, 0, 1}) {
                        for(int y: new int[]{-1, 0, 1}) {
                            if(i + x >= 0 && i + x < height && j + y >= 0 && j + y < width) {
                                total++;
                                sum += M[i + x][j + y];
                            }
                        }
                    }
                    result[i][j] = (int) Math.floor(sum/total);
                }
            }
            return result;
        }
    }
    

Log in to reply
 

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