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

我承认对于数组下标类的题目我极容易出错。。这题忘记每次重新初始化状态了。这种题目面试不太可能考,没什么思考的内容。纯粹考你细心。

public int[][] imageSmoother(int[][] M) {
        if (M == null || M.length == 0) return null;
        int len = M[0].length;
        int[][] res = new int[M.length][len];
        for (int i = 0; i < M.length; i++) {
            for (int j = 0; j < len; j++) {
                int left = 0, leftTop = 0, top = 0, rightTop = 0, right = 0, rightBottom = 0, bottom = 0, leftBottom = 0;
                int count = 1;
                if (i > 0) {
                    left = M[i - 1][j];
                    count++;
                    if (j > 0) {
                        leftTop = M[i - 1][j - 1];
                        count++;
                    }
                    if (j < len - 1) {
                        leftBottom = M[i - 1][j + 1];
                        count++;
                    }
                }
                if (j > 0) {
                    top = M[i][j - 1];
                    count++;
                    if (i < M.length - 1) {
                        rightTop = M[i + 1][j - 1];
                        count++;
                    }
                }
                if (i < M.length - 1) {
                    right = M[i + 1][j];
                    count++;
                    if (j < len - 1) {
                        rightBottom = M[i + 1][j + 1];
                        count++;
                    }
                }
                if (j < len - 1) {
                    bottom = M[i][j + 1];
                    count++;
                }
                int sum = left + leftTop + top + rightTop + right + rightBottom + bottom + leftBottom + M[i][j];
                int val = (int) Math.floor(sum / (float) count);
                res[i][j] = val;
            }
        }
        return res;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 原题是: Given a 2D integer matrix M representing the gray sc...
    小双2510阅读 405评论 0 1
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,959评论 0 23
  • 2003年,你是小学生了,上学路上,小鸟说,早早早,你为什么背着小书包 2004年,非典,操场上排队量体温,还没有...
    菀蔸阅读 218评论 0 1
  • 遇见他的那一刻,我不信一辈子。我什么都不信。 我本是女娇娥,又不是男儿郎。 后来, 我的灵魂为了他变的柔软,变的生...
    lnnn阅读 218评论 0 0