661. Image Smoother

 1 static int wing=[]()
 2 {
 3     std::ios::sync_with_stdio(false);
 4     cin.tie(NULL);
 5     return 0;
 6 }();
 7 
 8 class Solution 
 9 {
10 public:
11     bool valid(int i,int j,vector<vector<int>> &M)
12     {
13         if(i>=0&&i<M.size()&&j>=0&&j<M[0].size())
14             return true;
15         return false;
16     }
17     
18     vector<vector<int>> imageSmoother(vector<vector<int>>& M) 
19     {
20         int row=M.size(),col=M[0].size();
21         vector<vector<int>> res(row);
22         
23         if(row==0||col==0)
24             return res;
25         for(int i=0;i<row;i++)
26         {
27             vector<int> cur(col);
28             for(int j=0;j<col;j++)
29             {
30                 int sum=0;
31                 int count=0;
32                 for(int hor=-1;hor<2;hor++)
33                 {
34                     for(int dow=-1;dow<2;dow++)
35                     {
36                         if(valid(i+hor,j+dow,M))
37                         {
38                             count++;
39                             sum+=M[i+hor][j+dow];
40                         }
41                     }
42                 }
43                 cur[j]=(sum/count);
44             }
45             res[i]=cur;
46         }
47         return res;
48     }
49 };

设置一个判定函数,有效元素才进行累加和统计

猜你喜欢

转载自www.cnblogs.com/zhuangbijingdeboke/p/9156433.html