Leetcode - 661 Image Smoother (Easy)
题目描述:包含整数的二维矩阵 M 表示一个图片的灰度。你需要设计一个平滑器来让每一个单元的灰度成为平均灰度 (向下舍入) ,平均灰度的计算是周围的8个单元和它本身的值求平均,如果周围的单元格不足八个,则尽可能多的利用它们。
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
public int[][] imageSmoother(int[][] M) {
int m = M.length, n = M[0].length;
int[][] res = new int[m][n];
int[][] direction = new int[][]{{-1, -1}, {-1, 0}, {-1, 1},
{0, -1}, {0, 0}, {0, 1},
{1, -1}, {1, 0}, {1, 1}};
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int count = 0;
for (int k = 0; k < 9; k++) {
int x = i + direction[k][0], y = j + direction[k][1];
if (x >= 0 && x < m && y >= 0 && y < n) {
res[i][j] += M[x][y];
count++;
}
}
res[i][j] = res[i][j] / count;
}
}
return res;
}