661. Image Smoother
Given a 2D integer matrix M representing the gray scale of an image, you need to design a smoother to make the gray scale of each cell becomes the average gray scale (rounding down) of all the 8 surrounding cells and itself. If a cell has less than 8 surrounding cells, then use as many as you can.
Example 1:
Input: [[1,1,1], [1,0,1], [1,1,1]] Output: [[0, 0, 0], [0, 0, 0], [0, 0, 0]] Explanation: For the point (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0 For the point (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
C++(173ms):
1 class Solution { 2 public: 3 vector<vector<int>> imageSmoother(vector<vector<int>>& M) { 4 int n = M.size() ; 5 int m = M[0].size(); 6 if (n == 0 || m == 0) 7 return vector<vector<int>>() ; 8 vector<vector<int>> dirs = {{0,1},{0,-1},{1,0},{-1,0},{-1,-1},{1,1},{-1,1},{1,-1}}; 9 vector<vector<int>> res(n) ; 10 for(int i = 0 ; i < n ; i++){ 11 for (int j = 0 ; j < m ; j++){ 12 res[i].resize(m) ; 13 int sum = M[i][j] ; 14 int cnt = 1 ; 15 for(int k = 0 ; k < 8 ; k++){ 16 int x = i + dirs[k][0] ; 17 int y = j + dirs[k][1] ; 18 if (x < 0 || x > n-1 || y < 0 || y > m-1) 19 continue ; 20 sum += M[x][y] ; 21 cnt++ ; 22 } 23 res[i][j] = sum/cnt ; 24 } 25 } 26 return res ; 27 } 28 };
或者 vector<vector<int>> res(n , vector<int>(m,0)) ;