Clean Java Solution (~22 lines) with explanation


  • 0
    N

    All we really have to do here is add all possible cells around a given point.
    Let's say the give is (x,y) then the possible cells around it will be the following:

          (x-1,y-1)| (x-1,y) |(x-1,y+1)
          (x, y-1) |  {x,y}  |(x-1,y+1)
          (x+1,y-1)| (x+1,y) |(x+1,y+1)
    

    Simply check if the indices are in the range and add them to the total.

     public int[][] imageSmoother(int[][] M) {
            
            int row = M.length, col = M[0].length;       
            int[][] result = new int[row][col];            
            for(int i=0;i<row;++i){ 
                for(int j=0;j<col;++j){      
                    int total = 0, points = 0;
                         for(int k=i-1;k<i+2;++k){ 
                             if(k>-1 && k<row){
                                 for(int l=j-1;l<j+2;++l){      
                                      if (l>-1 && l<col){
                                          total+=M[k][l];        
                                          ++points;
                                      }
                                  }
                             }
                         }
                    result[i][j] = (int) Math.floor(total/(double)points);
                }
            }
            
            return result;
        }

Log in to reply
 

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