码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Image Smoother

时间:2017-09-11 23:32:25      阅读:390      评论:0      收藏:0      [点我收藏+]

标签:遍历   width   its   leetcode   sum   round   计算   code   each   

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

标签:遍历   width   its   leetcode   sum   round   计算   code   each   

原文地址:http://www.cnblogs.com/immjc/p/7507869.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!