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.

这里有点小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];
    }
}
```.
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容