Super clean and easy solution


  • 2
    Z

    Given a 2D integer matrix M representing the gray scale of an image, you need to design a smoother to make the gray scale of each cell becomes the average gray scale (rounding down) of all the 8 surrounding cells and itself. If a cell has less than 8 surrounding cells, then use as many as you can.

    for every element, represented by M[i][j], the average of M[i][j] and its neighbors should be the sum of (itself and its valid neighbors' value) divided by valid count

    for every M[i][j], there are 8 neighbors, some of them may be index out of boundary, If it's neighbor's index is valid, then add it to sum, and count++

    code below

    class Solution {
        public int[][] imageSmoother(int[][] M) {
            if(M==null||M.length==0) return new int[][];
            int n=M.length;
            int m=M[0].length;
            int res[][]=new int[n][m];
            
            for(int i=0;i<n;i++){
                for(int j=0;j<m;j++){
                    res[i][j]=avg(M,i,j,n,m);
                }
            }
            return res;
        }
        
        public int avg(int[][] M,int x,int y,int n,int m){
            int sum=0;
            int count=0;
            int[] valueAndCount=new int[]{0,0};
            
            for(int[] co:new int[][]{{x,y},{x,y-1},{x,y+1},{x-1,y},{x+1,y},{x+1,y-1},{x+1,y+1},{x-1,y-1},{x-1,y+1}}){
                valueAndCount=valueAndCount(M,co[0],co[1],n,m);
                sum+=valueAndCount[0];
                count+=valueAndCount[1]; 
            }
            return sum/count;
        }
        
        public int[] valueAndCount(int[][] M,int x,int y,int n,int m){
            boolean valid=x>=0&&x<n&&y>=0&&y<m;
            return new int[]{valid?M[x][y]:0,valid?1:0};
        }
    }
    
    

Log in to reply
 

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