基本思路:主要是对边界情况的处理,行设为i,列设为j。对行,取0和i-1的较大值,取m和i+2的较小值(因为range取不到右边界)。对列,取j-1和0的较大值,取n和j+2的较大值,然后只需要按照题意遍历这些点然后加起来取平均即可。代码如下:
class Solution:
def imageSmoother(self, img: List[List[int]]) -> List[List[int]]:
m,n=len(img),len(img[0])
ans = [[0] * n for _ in range(m)]
for i in range (m):
for j in range (n):
tot,num=0,0
for x in range (max(i-1,0),min(m,i+2)):
for y in range (max(j-1,0),min(j+2,n)):
tot+=img[x][y]
num+=1
ans[i][j]=tot//num
return ans