661.Image Smoother

Test cases

1
2
3
4
5
6
[[1]]
[[1,1,1],[1,0,1],[1,1,1]]
[[1,2,3,4,5,6,7]]
[[1,2,3,4,5,6,7],[2,1,4,6,7,4,8]]
[[1],[2],[4],[4],[5]]
[[1,3],[2,5],[4,4],[8,4],[9,5]]

Solution 1: accepted 35ms

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public int[][] imageSmoother(int[][] M) {
if (M.length == 0) return M;
int [][] A = new int[M.length][M[0].length];
for (int row = 0; row < M.length; row++) {
for (int col = 0; col < M[0].length; col++) {
int sum = 0;
int xStart = row == 0? 0 : -1;
int xEnd = row == M.length - 1? 0 : 1;
int yStart = col == 0? 0 : -1;
int yEnd = col == M[0].length - 1? 0: 1;
int divisor = 0;
for (int x = xStart; x <= xEnd; x++) {
for (int y = yStart; y <= yEnd; y++) {
sum += M[row + x][col + y];
divisor ++;
}
}
A[row][col] = (int)(sum / (double)divisor);
}
}
return A;
}