Given a 2D integer matrix M representing the gray scale of an image, you need to design a smoother to make the gray scale of each cell becomes the average gray scale (rounding down) of all the 8 surrounding cells and itself. If a cell has less than 8 surrounding cells, then use as many as you can.
Example 1:
Input:
[[1,1,1],
[1,0,1],
[1,1,1]]
Output:
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
Explanation:
For the point (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0
For the point (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0
For the point (1,1): floor(8/9) = floor(0.88888889) = 0
图片平滑,每个像素求它和它8邻域的平均值取floor,也就是向下取整
思路:
直接暴力解决,但是注意边界条件
而且注意java的floor函数返回是double,要down cast
public int[][] imageSmoother(int[][] M) {
if(M == null || M.length == 0) {
return new int[1][1];
}
int m = M.length;
int n = M[0].length;
int[][] result = new int[m][n];
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
int up = (i == 0) ? i : i-1;
int down = (i == m-1) ? i : i+1;
int left = (j == 0) ? j : j-1;
int right = (j == n-1) ? j : j+1;
result[i][j] = smoother(M, up, down, left, right);
}
}
return result;
}
int smoother(int[][] M, int up, int down, int left, int right) {
float tmp = 0f;
int count = 0;
for(int i = up; i <= down; i++) {
for(int j = left; j <= right; j++) {
tmp += M[i][j];
count ++;
}
}
return (int)Math.floor(tmp/count);
}