leetcode-661-easy
Image Smoother
An image smoother is a filter of the size 3 x 3 that can be applied to each cell of an image
by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother).
If one or more of the surrounding cells of a cell is not present, we do not consider it in the average (i.e., the average of the four cells in the red smoother).
Given an m x n integer matrix img representing the grayscale of an image, return the image after applying the smoother on each cell of it.
Example 1:
Input: img = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[0,0,0],[0,0,0],[0,0,0]]
Explanation:
For the points (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0
For the points (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
Example 2:
Input: img = [[100,200,100],[200,50,200],[100,200,100]]
Output: [[137,141,137],[141,138,141],[137,141,137]]
Explanation:
For the points (0,0), (0,2), (2,0), (2,2): floor((100+200+200+50)/4) = floor(137.5) = 137
For the points (0,1), (1,0), (1,2), (2,1): floor((200+200+50+200+100+100)/6) = floor(141.666667) = 141
For the point (1,1): floor((50+200+200+200+200+100+100+100+100)/9) = floor(138.888889) = 138
Constraints:
m == img.length
n == img[i].length
1 <= m, n <= 200
0 <= img[i][j] <= 255
思路一:先用一圈 0 包围住数组,然后依次计算每个 cell 的值。看了一下官方解答,都是体力活
public int[][] imageSmoother(int[][] img) {
int m = img.length;
int n = img[0].length;
int[][] ans = new int[m][n];
int[][] temp = new int[m + 2][n + 2];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
temp[i + 1][j + 1] = img[i][j];
}
}
for (int i = 1; i < m + 1; i++) {
for (int j = 1; j < n + 1; j++) {
int sum = imageSmootherSum(temp, i, j);
int count = imageSmootherCount(m + 2, n + 2, i, j);
ans[i - 1][j - 1] = sum / count;
}
}
return ans;
}
public int imageSmootherSum(int[][] temp, int i, int j) {
return temp[i - 1][j - 1] + temp[i - 1][j] + temp[i - 1][j + 1] +
temp[i][j - 1] + temp[i][j] + temp[i][j + 1] +
temp[i + 1][j - 1] + temp[i + 1][j] + temp[i + 1][j + 1];
}
public int imageSmootherCount(int m, int n, int i, int j) {
int width = 3;
int height = 3;
if (j == 1) {
width--;
}
if (j == n - 2) {
width--;
}
if (i == 1) {
height--;
}
if (i == m - 2) {
height--;
}
return width * height;
}