The two-dimensional matrix M containing integers represents the gray level of a picture. You need to design a smoother to make the gray level of each cell become the average gray level (rounded down). The average gray level is calculated by averaging the surrounding 8 cells and its own value. If the surrounding cells are insufficient Eight, use them as much as possible.
Example 1:
Input: [[1,1,1],
[1,0,1],
[1,1,1]]
Output: [[0, 0, 0],
[0, 0, 0],
[0, 0 ,0))
Explanation: For point (0,0), (0,2), (2,0), (2,2): average (3/4) = average (0.75) = 0
for point (0, 1), (1,0), (1,2), (2,1): average (5/6) = average (0.83333333) = 0
for point (1,1): average (8/9) = average (0.88888889) = 0
Note:
The range of integers in the given matrix is [0, 255].
The range of the length and width of the matrix are both [1, 150].
Source: LeetCode
Link: https://leetcode-cn.com/problems/image-smoother
Method 1: Traverse the matrix
For each cell in the matrix, find all 9 adjacent cells including itself.
Then, we want to save the sum of all neighbors in ans[r][c], and record the number of neighbors count at the same time. The final answer is to divide the sum by the number of neighbors.
public int[][] imageSmoother(int[][] M) {
int R = M.length, C = M[0].length;
int[][] ans = new int[R][C];
for (int r = 0; r < R; r++)
for (int c = 0; c < C; c++) {
int count = 0;
for (int nr = r - 1; nr <= r + 1; nr++)
for (int nc = c - 1; nc <= c + 1; nc++) {
if (nr >= 0 && nr < R && nc >= 0 && nc < C) {
ans[r][c] += M[nr][nc];
count++;
}
}
ans[r][c] /= count;
}
return ans;
}