Last Updated on 2023-12-19 by Clay
題目
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
解題思路
這題呈現了何為 simple is fit —— 最簡單的解法也是最好的。由於題目限定要讓每個像素點取無條件捨去的周圍平均值(也就是距離本身像素點的周圍 1 格,也就是最多的情況下一共 9 個像素值,超過邊界則不計),所以我們只需要遍歷輸入圖片中的每一個像素點,並且將其周圍所有的值加總即可。
C++ 範例程式碼
class Solution {
public:
vector<vector<int>> imageSmoother(vector<vector<int>>& img) {
// Init
int m = img.size();
int n = img[0].size();
vector<vector<int>> newImg(m, vector<int>(n, 0));
// Smoothing
for (int i=0; i<m; ++i) {
for (int j=0; j<n; ++j) {
int _count = 0;
int _sum = 0;
for (int _dx=-1; _dx<=1; ++_dx) {
for (int _dy=-1; _dy<=1; ++_dy) {
int x = i + _dx;
int y = j + _dy;
if (x < 0 || y < 0 || x >= m || y >= n) {
continue;
}
++_count;
_sum += img[x][y];
}
}
newImg[i][j] = _sum / _count;
}
}
return newImg;
}
};
Python 範例程式碼
class Solution:
def imageSmoother(self, img: List[List[int]]) -> List[List[int]]:
# Init
m = len(img)
n = len(img[0])
newImg = [[0] * n for _ in range(m)]
# Smoothing
for i in range(m):
for j in range(n):
_count = 0
_sum = 0
for _dx in range(-1, 2, 1):
for _dy in range(-1, 2, 1):
x = i + _dx
y = j + _dy
if 0 <= x < m and 0 <= y < n:
_count += 1
_sum += img[x][y]
newImg[i][j] = math.floor(_sum / _count)
return newImg