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

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].

解题思路:

暂时想不到好办法。。用最蠢的M*N*8算了。

  1. class Solution {  
  2. public:  
  3.     vector<vector<int>> imageSmoother(vector<vector<int>>& M) {  
  4.         if(M.size()==0) return M;  
  5.         vector<vector<int>> ret = M;  
  6.         vector<vector<int>> store;  
  7.         for(int i=0;i<M.size();i++)  
  8.             for(int j=0;j<M[0].size();j++)  
  9.                 ret[i][j]=0;  
  10.           
  11.         for(int i=0;i<M.size();i++){  
  12.             for(int j=0;j<M[0].size();j++){  
  13.             int sum=0;  
  14.             int count=0;  
  15.                 sum+=M[i][j];count++;  
  16.                 if(j-1>=0) {sum+=M[i][j-1];count++;}  
  17.                 if(j+1<M[0].size()) {sum+=M[i][j+1];count++;}  
  18.                   
  19.                 if(i-1>=0){  
  20.                 sum+=M[i-1][j];count++;  
  21.                 if(j-1>=0) {sum+=M[i-1][j-1];count++;}  
  22.                 if(j+1<M[0].size()) {sum+=M[i-1][j+1];count++;}  
  23.                       
  24.                 }  
  25.                 if(i+1<M.size()){  
  26.                 sum+=M[i+1][j];count++;  
  27.                 if(j-1>=0) {sum+=M[i+1][j-1];count++;}  
  28.                 if(j+1<M[0].size()) {sum+=M[i+1][j+1];count++;}  
  29.                       
  30.                 }  
  31.                 ret[i][j]= sum/count;  
  32.                   
  33.             }      
  34.         }  
  35.   
  36.           
  37.         return ret;  
  38.           
  39.     }  
  40. };  
原文地址:https://www.cnblogs.com/liangyc/p/8822121.html