【Python】【难度:简单】Leetcode 661. 图片平滑器

包含整数的二维矩阵 M 表示一个图片的灰度。你需要设计一个平滑器来让每一个单元的灰度成为平均灰度 (向下舍入) ,平均灰度的计算是周围的8个单元和它本身的值求平均,如果周围的单元格不足八个,则尽可能多的利用它们。

示例 1:

输入:
[[1,1,1],
 [1,0,1],
 [1,1,1]]
输出:
[[0, 0, 0],
 [0, 0, 0],
 [0, 0, 0]]
解释:
对于点 (0,0), (0,2), (2,0), (2,2): 平均(3/4) = 平均(0.75) = 0
对于点 (0,1), (1,0), (1,2), (2,1): 平均(5/6) = 平均(0.83333333) = 0
对于点 (1,1): 平均(8/9) = 平均(0.88888889) = 0
注意:

给定矩阵中的整数范围为 [0, 255]。
矩阵的长和宽的范围均为 [1, 150]。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/image-smoother
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

class Solution(object):
    def imageSmoother(self, M):
        """
        :type M: List[List[int]]
        :rtype: List[List[int]]
        """
        res=[[0 for i in range(len(M[0]))] for j in range(len(M))]

        for i in range(len(M)):
            for j in range(len(M[0])):
                temp = []
                temp.append(M[i][j])
                #左
                if j-1>=0:
                    temp.append(M[i][j-1])
                #右
                if j+1<=len(M[0])-1:
                    temp.append(M[i][j+1])
                #上
                if i-1>=0:
                    temp.append(M[i-1][j])
                #下
                if i+1<=len(M)-1:
                    temp.append(M[i+1][j])
                #左上
                if i-1>=0 and j-1>=0:
                    temp.append(M[i-1][j-1])
                #左下
                if i+1<=len(M)-1 and j-1>=0:
                    temp.append(M[i+1][j-1])
                #右上
                if i-1>=0 and j+1<=len(M[0])-1:
                    temp.append(M[i-1][j+1])
                #右下
                if i+1<=len(M)-1 and j+1<=len(M[0])-1:
                    temp.append(M[i+1][j+1])

                res[i][j]=sum(temp)//len(temp)
        return res

 

执行结果:

通过

显示详情

执行用时:536 ms, 在所有 Python 提交中击败了78.75%的用户

内存消耗:12.9 MB, 在所有 Python 提交中击败了100.00%的用户

你可能感兴趣的:(leetcode)