661. 图片平滑器
-
[题目链接](661. 图片平滑器 - 力扣(LeetCode))
-
解题思路
- 题目不难,关键是怎么写得【优雅】
- 一般这种枚举的题,我们可以定义一个【方向】数组,然后直接for循环遍历这个【方向】数组,代码会更优雅,直接看代码
-
代码
class Solution { public: vector<vector<int>> imageSmoother(vector<vector<int>>& img) { int m = img.size(); int n = img[0].size(); // 这个就是【方向】数组 vector<vector<int>> dir{{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 0}, {0, 1}, {1, -1}, {1, 0}, {1, 1}}; vector<vector<int>> ans(m, vector<int>(n, 0)); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { int cur = 0; int valid = 0; for (int k = 0; k < 9; ++k) { int next_i = i + dir[k][0]; int next_j = j + dir[k][1]; if (next_i < m && next_i >= 0 && next_j < n && next_j >= 0) { cur += img[next_i][next_j]; valid++; } } ans[i][j] = cur / valid; } } return ans; } };