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;
    }

你可能感兴趣的:(661. Image Smoother)