1. 程式人生 > >[LeetCode] Image Smoother

[LeetCode] Image Smoother

一個 blog cell size cto cells 二維 sum all

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

對每一個點及其周圍的值求平均值作為新的值賦予該點。首先要判斷一個點周圍有多少個有效點。利用isVaild判斷有效點。然後遍歷原二維數組,然後計算每個點周圍的有效點平均值賦給該點後壓入數組。

class Solution {
public:
    vector<vector<int>> imageSmoother(vector<vector<int>>& M) {
        vector<vector<int
>> res; int rows = M.size(), cols = M[0].size(); if (rows == 0 || cols == 0) return res; for (int i = 0; i != rows; i++) { vector<int> cur; for (int j = 0; j != cols; j++) { int sum = 0; int cnt = 0; for (int x = -1; x < 2; x++) { for (int y = -1; y < 2; y++) { if (isVaild(i + x, j + y, M)) { cnt++; sum += M[x + i][y + j]; } } } cur.push_back(sum / cnt); } res.push_back(cur); } return res; } bool isVaild(int i, int j, vector<vector<int>>& M) { if (i >= 0 && i < M.size() && j >= 0 && j < M[0].size()) return true; return false; } }; // 169 ms

[LeetCode] Image Smoother