题目描述:包含整数的二维矩阵 M 表示一个图片的灰度。你需要设计一个平滑器来让每一个单元的灰度成为平均灰度 (向下舍入) ,平均灰度的计算是周围的8个单元和它本身的值求平均,如果周围的单元格不足八个,则尽可能多的利用它们。
例子:
输入:
[[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]。
解题思路:把二维数组的上下左右都填满0
[[0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 1, 0, 1, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0]]
分三类情况4个顶点除以4,4条除了顶点的边除以6,其他点除以9
python代码:
class Solution(object):
def imageSmoother(self, M):
"""
:type M: List[List[int]]
:rtype: List[List[int]]
"""
row = len(M)
column = len(M[0])
t = []
t.insert(0,[0] * (column + 2))
for i in M:
i.insert(0,0)
i.append(0)
t.append(i)
t.append([0] * (column + 2))
temp = []
for i in range(1,row+1):
tt = []
for j in range(1,column+1):
s = t[i-1][j-1] + t[i-1][j] + t[i-1][j+1] + t[i][j-1]+ t[i][j] +t[i][j+1]+t[i+1][j-1]+t[i+1][j]+t[i+1][j+1]
if row == 1 and column == 1: #只有一个数
tt.append(s)
elif row == 1 and column != 1:
if j == 1 or j == column: #只有一行
tt.append(s/2)
else:
tt.append(s/3)
elif column == 1 and row != 1: #只有一列
if i == 1 or i == row:
tt.append(s/2)
else:
tt.append(s/3)
else: #正常二维数组
if (i == 1 or i== row) and (j == 1 or j ==column):
tt.append(int(s/4))
elif ((j == 1 or j==column) and(i!=1 or i!=row) )or ((i==1 or i==row) and(j !=1 or j!=row)):
tt.append(int(s/6))
else:
tt.append(int(s/9))
temp.append(tt)
return temp