跳到主要内容

661.图片平滑器

链接:661.图片平滑器
难度:Easy
标签:数组、矩阵
简介:给你一个表示图像灰度的 m x n 整数矩阵 img ,返回对图像的每个单元格平滑处理后的图像 。

题解 1 - cpp

  • 编辑时间:2022-03-16
  • 执行用时:44ms
  • 内存消耗:21.1MB
  • 编程语言:cpp
  • 解法介绍:遍历。
class Solution {
public:
constexpr static int dirs[8][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0},
{1, 1}, {1, -1}, {-1, 1}, {-1, -1}};
vector<vector<int>> imageSmoother(vector<vector<int>>& img) {
int n = img.size(), m = img[0].size();
vector<vector<int>> ans(n, vector<int>(m));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int val = img[i][j], cnt = 1;
for (int k = 0; k < 8; k++) {
int ni = i + dirs[k][0], nj = j + dirs[k][1];
if (ni < 0 || ni == n || nj < 0 || nj == m) continue;
val += img[ni][nj];
cnt++;
}
ans[i][j] = val / cnt;
}
}
return ans;
}
};

题解 2 - undefined

  • 编辑时间:2024-11-18
  • 执行用时:127ms
  • 内存消耗:17.56MB
  • 编程语言:undefined
  • 解法介绍:遍历。
dirs2 = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
class Solution:
def imageSmoother(self, img: List[List[int]]) -> List[List[int]]:
n = len(img)
m = len(img[0])
res = []
for i in range(n):
item = []
for j in range(m):
c = v = 0
c += 1
v += img[i][j]
for dir in dirs2:
ni = i + dir[0]
nj = j + dir[1]
if 0 <= ni < n and 0 <= nj < m:
c += 1
v += img[ni][nj]
item.append(v // c)
res.append(item)
return res