# Clean and Easy to Understand Java Solution(With Comments), beats 96%

• ``````  // I write a separate function which calculates the average value of that pixel and take care of indexing issue in that method, explained in comments in code
class Solution {

public int[][] imageSmoother(int[][] M) {

int[][] res = new int[M.length][M[0].length];

for(int i=0; i<M.length; i++){
for(int j=0; j<M[0].length;j++){
res[i][j] = getVal(M,i,j);
}
}

return res;
}

private int getVal(int[][] arr, int i, int j){
//Start index for row would be maximum of 0 or i-1. For row 0, startI will be 0 and for row 2, startI will be 1. Same can be done for columns.
int startI = Math.max(0,i-1);
int startJ = Math.max(0,j-1);

// Similarly, we need minimum of i+1 and last index that is arr.length - 1. We take maximum in this case as shown below.
int endI = Math.min(i+1,arr.length-1);
int endJ = Math.min(j+1,arr[0].length-1);

int count = 0;
int res = 0;

// Loop over start value to end value
for(int k=startI; k<=endI;k++){
for(int l=startJ; l<=endJ;l++){
count++;
res += arr[k][l];
}
}
return res/count;
}}'''``````

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