leetcode 661. Image Smoother

来源:互联网 发布:windows redis自启动 编辑:程序博客网 时间:2024/06/08 04:29

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

本题题意很简单,直接暴力遍历即可

代码如下:

#include <iostream>#include <vector>#include <map>#include <set>#include <queue>#include <stack>#include <string>#include <climits>#include <algorithm>#include <sstream>#include <functional>#include <bitset>#include <numeric>#include <cmath>#include <regex>using namespace std;class Solution {public:    vector<vector<int>> imageSmoother(vector<vector<int>>& m)     {        int row = m.size(), col = m[0].size();        vector<vector<int>> res(row, vector<int>(col, 0));        for (int i = 0; i < row; i++)        {            for (int j = 0; j < col; j++)            {                res[i][j] = getAverage(i, j, m);            }        }        return res;    }    int getAverage(int x, int y, vector<vector<int>>& m)    {        int row = m.size(), col = m[0].size();        int sum = 0, count = 0;        for (int i = max(0, x - 1); i <= min(row - 1, x + 1); i++)        {            for (int j = max(0, y - 1); j <= min(col - 1, y + 1); j++)            {                count++;                sum += m[i][j];            }        }        return floor((double)sum / count);    }};
原创粉丝点击