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
思路:
1,初始化一个矩阵NM,矩阵周围都为-1(因为图像的像素值不可能为负数),中间与输入矩阵相同
2,遍历NM矩阵,遍历的范围不包括-1的值,也就是只遍历矩阵M中的值
遍历NM中每个点的八邻域,若值不为-1,则正常计算,否则不加,并且除数-1
将得到的平均值放在ans中
#pragma once
#include <iostream>
#include<vector>
using namespace std;
class Solution {
public:
vector<vector<int>> imageSmoother(vector<vector<int>>& M) {
vector<vector<int>> NM(M.size() + 2,vector <int>( M[0].size() + 2));
vector<vector<int>> ans=M;//返回值ans
int sum = 0;
//将M用-1包围一圈
//NM.resize((M.size() + 2, M[0].size() + 2));
for (int i = 0; i < NM.size(); i++)
{
for (int j = 0; j < NM[0].size(); j++)
{
if (i == 0|| j == 0||i== NM.size()-1||j== NM[0].size()-1)
{
NM[i][j]=-1;
}
else
{
NM[i][j] = M[i - 1][j - 1];
}
}
}
//当等于-1时,则少加并少除一个数,遍历除了额外添加的-1以外的每一个变量
for (int i = 1; i < NM.size()-1; i++)
{
for (int j = 1; j < NM[0].size()-1; j++)
{
int t = 9;
int sum = 0;
for (int a = i - 1; a <= i + 1; a++)
{
for (int b = j - 1; b <= j + 1; b++)
{
//如果周围有-1,则表示在周边,则-1不参与运算,并且除数t减少
if (NM[a][b] == -1)
{
t--;
}
else
{
sum += NM[a][b];
}
}
//计算出该点平滑后的值
ans[i-1][j-1] = sum / t;
}
}
}
return ans;
}
};