Accepted Java Solution

• All test cases passed. Are there any improvements I can make in here.

``````class Solution {
public int[][] imageSmoother(int[][] M) {

if(M.length<0 || M[0].length<0)
return new int[][]{{-1}};

int min_i, min_j, max_i, max_j;
min_i = min_j = 0;
max_i = M.length;
max_j = M[0].length;

int[][] result = new int[max_i][max_j];
for(int result_i=0; result_i<max_i; result_i++) {
for(int result_j=0; result_j<max_j; result_j++) {
int sum, count;
sum = M[result_i][result_j]; count=1;
if(result_i-1>=min_i && result_j-1>=min_j)  { sum+=M[result_i-1][result_j-1]; count++; }
if(result_i-1>=min_i)                       { sum+=M[result_i-1][result_j]; count++; }
if(result_i-1>=min_i && result_j+1<max_j)   { sum+=M[result_i-1][result_j+1]; count++; }
if(result_j-1>=min_j)                       { sum+=M[result_i][result_j-1]; count++; }
if(result_j+1<max_j)                        { sum+=M[result_i][result_j+1]; count++; }
if(result_i+1<max_i && result_j-1>=min_j)   { sum+=M[result_i+1][result_j-1]; count++; }
if(result_i+1<max_i)                        { sum+=M[result_i+1][result_j]; count++; }
if(result_i+1<max_i && result_j+1<max_j)    { sum+=M[result_i+1][result_j+1]; count++; }

result[result_i][result_j] = (int)Math.floor(sum/count);
}
}
return result;
}
}
``````

• Actually you can iterate the Array by utilizing two variables:

• i, j : [-1, +1]

See following code:

``````        for(int i = -1; i<=1; i++){
for(int j=-1; j<=1; j++){
if(x+i < len1  && x+i >= 0 && y+j <len2 && y+j >= 0){ // len1: outer array length; len2: inner array length
sum += data[x+i][y+j];
count+=1;
}
}
}
``````

It will allow you to iterate all 8 surrounding cells and itself.

• @HitNoah Thank you for the suggestion.

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