661. Image Smoother

问题:

处理给定数组,(平滑处理)使得每个元素=周围+自己共9个元素的平均值。(若没有9个元素,则是周围一圈+自己元素的平均值)

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
Note: 1.The value in the given matrix is in the range of [0, 255]. 2.The length and width of the given matrix are in the range of [1, 150].

  

解决方法:顺次计算 [i-1] ~ [i+1], [j-1] ~ [j+1]

tip:需要注意边界值情况

解决:if [i-1]<0 || [i+1]>row-1 || [j-1]<0 || [j+1]>col-1; then 不计算

代码参考:

 1 class Solution {
 2 public:
 3     vector<vector<int>> imageSmoother(vector<vector<int>>& M) {
 4         int rows = M.size();
 5         if(rows==0) return M;
 6         int cols = M[0].size();
 7         vector<vector<int>> res(rows, vector<int>(cols, 0));
 8         for(int i=0; i<rows; i++){
 9             for(int j=0; j<cols; j++){
10                 int sum=0;
11                 int count=0;
12                 for(int x=(i-1)>=0?i-1:0;x<=((i+1)<rows?i+1:rows-1);x++){
13                     for(int y=(j-1)>=0?j-1:0;y<=((j+1)<cols?j+1:cols-1);y++){
14                         sum+=M[x][y];
15                         count++;
16                     }
17                 }
18                 res[i][j]=sum/count;
19             }
20         }
21         return res;
22     }
23 };

 

posted @ 2020-03-15 13:38  habibah_chang  阅读(92)  评论(0编辑  收藏  举报