# 661. Image Smoother

• Time: $O(mn)$
• Space: $O(mn)$
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 class Solution { public: vector> imageSmoother(vector>& M) { const int m = M.size(); const int n = M[0].size(); vector> ans(m, vector(n)); for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) { int ones = 0; int count = 0; for (int x = max(0, i - 1); x < min(m, i + 2); ++x) for (int y = max(0, j - 1); y < min(n, j + 2); ++y) { ones += M[x][y]; ++count; } ans[i][j] = ones / count; } return ans; } }; 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 class Solution { public int[][] imageSmoother(int[][] M) { final int m = M.length; final int n = M[0].length; int ans[][] = new int[m][n]; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) { int ones = 0; int count = 0; for (int y = Math.max(0, i - 1); y < Math.min(m, i + 2); ++y) for (int x = Math.max(0, j - 1); x < Math.min(n, j + 2); ++x) { ones += M[y][x]; ++count; } ans[i][j] = ones / count; } return ans; } } 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 class Solution: def imageSmoother(self, M: List[List[int]]) -> List[List[int]]: m = len(M) n = len(M[0]) ans = [[0 for j in range(n)] for i in range(m)] for i in range(m): for j in range(n): ones = 0 count = 0 for y in range(max(0, i - 1), min(m, i + 2)): for x in range(max(0, j - 1), min(n, j + 2)): ones += M[y][x] count += 1 ans[i][j] = ones // count return ans