美文网首页程序员
661. Image Smoother

661. Image Smoother

作者: namelessEcho | 来源:发表于2017-09-25 12:07 被阅读0次

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.

这里有点小trick,关于越界的问题,这里我写了一个helper来处理这个问题,看了一下其他答案,大多很繁琐,这里用函数包裹来解决越界问题是比较好的选择。

class Solution {
    public int[][] imageSmoother(int[][] M) {
        int col = M[0].length;
        int row = M.length;
        int[][] result = new int[row][col];
        for(int i = 0 ;i<row;i++)
        {
            for(int j = 0 ;j<col;j++)
            {
                result[i][j]=avg(M,i,j);
            }
        }
        return result ;
    }
    private int avg (int[][] M,int i ,int j )
    {
        int col = M[0].length;
        int row = M.length;
        int count = 0 ;
        int sum = 0 ;
        for(int k =i-1;k<=i+1;k++)
        {
            for(int h = j-1;h<=j+1;h++)
            {
                int val = helper(M,k,h);
                if(val!=-1)
                {
                    count++;
                    sum+=val;
                }
            }
        }
        return sum/count;
    }
    private int helper (int[][] M,int k,int h)
    {
        if(k<0||k==M.length) return -1;
        if(h<0||h==M[0].length) return -1;
        return M[k][h];
    }
}
```.

相关文章

网友评论

    本文标题:661. Image Smoother

    本文链接:https://www.haomeiwen.com/subject/ygwrextx.html