Easy Java Straightforward solution


  • 0
    M
    class Solution {
        public int[][] imageSmoother(int[][] M) {
            if(M==null || M.length==0 ) return M;
            
            int[] dx = {-1,0,1,1,1,0,-1,-1};
            int[] dy = {1,1,1,0,-1,-1,-1,0};
            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++)
                {
                    int count = 1,sum=M[i][j];
                    for(int k=0;k<8;k++)
                    {
                        if(isValid(M,i+dx[k],j+dy[k]))
                        {
                            //System.out.println((i+dx[k]) +" "+(j+dy[k]));
                            sum+=M[i+dx[k]][j+dy[k]];
                            count++;
                        }
                    }
                    //System.out.println(sum+" "+count);
                    ret[i][j] = (sum)/(count);
                }
            }
            return ret;
            
        }
        
        boolean isValid(int[][] M,int x,int y)
        {
            if(x<0 || x>=M.length || y<0 || y>=M[0].length)
                return false;
            
            return true;
        }
    }
    

Log in to reply
 

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