classSolution { public: vector<vector<int>> imageSmoother(vector<vector<int>>& img) { vector<vector<int>> ans(img.size(), vector<int>(img[0].size())); for (int i = 0; i < img.size(); i++) { for (int j = 0; j < img[0].size(); j++) { int cnt = 0, s = 0; for (int x = -1; x <= 1; x++) { for (int y = -1; y <= 1; y++) { int nx = i + x, ny = j + y; if (0 <= nx && nx < img.size() && 0 <= ny && ny < img[0].size()) { s += img[nx][ny]; cnt++; } } } ans[i][j] = s / cnt; } } return ans; } };
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
from typing importList
classSolution: defimageSmoother(self, img: List[List[int]]) -> List[List[int]]: ans = [[0for _ inrange(len(img[0]))] for _ inrange(len(img))] for i inrange(len(img)): for j inrange(len(img[0])): cnt, s = 0, 0 for dx inrange(-1, 2): for dy inrange(-1, 2): x, y = i + dx, j + dy if0 <= x < len(img) and0 <= y < len(img[0]): cnt += 1 s += img[x][y] ans[i][j] = s // cnt return ans
classSolution { publicint[][] imageSmoother(int[][] img) { int[][] ans = newint[img.length][img[0].length]; for (inti=0; i < img.length; i++) { for (intj=0; j < img[0].length; j++) { intcnt=0, s = 0; for (intdx= -1; dx <= 1; dx++) { for (intdy= -1; dy <= 1; dy++) { intx= i + dx, y = j + dy; if (0 <= x && x < img.length && 0 <= y && y < img[0].length) { cnt++; s += img[x][y]; } } } ans[i][j] = s / cnt; } } return ans; } }
Go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
package main
funcimageSmoother(img [][]int) (ans [][]int) { ans = make([][]int, len(img)) for i := range ans { ans[i] = make([]int, len(img[0])) for j := range ans[i] { cnt, s := 0, 0 for _, row := range img[max(0, i - 1):min(len(img), i + 2)] { for _, val := range row[max(0, j - 1):min(len(img[0]), j + 2)] { cnt++ s += val } } ans[i][j] = s / cnt } } return ans }