1 class Solution(object): 2 def imageSmoother(self, M): 3 """ 4 :type M: List[List[int]] 5 :rtype: List[List[int]] 6 """ 7 # padding:在原矩阵周围加上一圈非有效数字:-10,便于处理边缘元素 8 m = len(M[0]) 9 N = [[-10] + i + [-10] for i in M] 10 N = [[-10] * (m + 2)] + N + [[-10] * (m + 2)] 11 for i in range(1, len(N) - 1): 12 for j in range(1, len(N[0]) - 1): 13 # 当前元素及其周围的八个元素:九宫格 14 total = [N[i - 1][j - 1], N[i - 1][j], N[i - 1][j + 1], N[i][j - 1], N[i][j], N[i][j + 1], 15 N[i + 1][j - 1], N[i + 1][j], N[i + 1][j + 1]] 16 # 统计包括当前九宫格内元素的和 17 sumthis = 0 18 # 统计当前九宫格内非有效元素的个数,用于求均值 19 numextra = 0 20 # 求九宫格内有效元素的和 21 for digit in total: 22 if digit != -10: 23 sumthis += digit 24 else: 25 numextra += 1 26 # 求均值并赋给原矩阵对应元素 27 M[i - 1][j - 1] = sumthis // (9 - numextra) 28 return M 29 30 31 if __name__ == '__main__': 32 solution = Solution() 33 print(solution.imageSmoother([[1, 1, 1], [1, 0, 1], [1, 1, 1]]))