leetcode 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.
Example 1:
Input: [[1,1,1], [1,0,1], [1,1,1]] Output: [[0, 0, 0], [0, 0, 0], [0, 0, 0]] Explanation: For the point (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0 For the point (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0 For the point (1,1): floor(8/9) = floor(0.88888889) = 0
Note:
- The value in the given matrix is in the range of [0, 255].
- The length and width of the given matrix are in the range of [1, 150].
不修改M:
class Solution(object): def imageSmoother(self, M): """ :type M: List[List[int]] :rtype: List[List[int]] """ row = len(M) col = len(M[0]) R = [[0 for i in range(col)] for j in range(row)] def get_avg(M, i, j): diff_pos = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)] s = M[i][j] l = 1 for x,y in diff_pos: if 0<=i+x<row and 0<=j+y<col: s += M[i+x][j+y] l += 1 return s//l for i in xrange(0, row): for j in xrange(0, col): R[i][j] = get_avg(M, i, j) return R
修改M:
class Solution(object):
def imageSmoother(self, M):
"""
:type M: List[List[int]]
:rtype: List[List[int]]
"""
row = len(M)
col = len(M[0])
def get_avg(M, i, j):
s = l = 0
for x in xrange(-1, 2):
for y in xrange(-1, 2):
if 0<=i+x<row and 0<=j+y<col:
s += (M[i+x][j+y] & 0xff)
l += 1
return (s//l) <<8
for i in xrange(0, row):
for j in xrange(0, col):
M[i][j] += get_avg(M, i, j)
for i in xrange(0, row):
for j in xrange(0, col):
M[i][j] >>= 8
return M
记得细节:M[i][j] += get_avg(M, i, j) 是+= 而非=
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
2017-04-01 信息检索导论的课件——http://home.ustc.edu.cn/~zhufengx/ir/pdf/
2017-04-01 通过Mesos、Docker和Go,使用300行代码创建一个分布式系统
2017-04-01 varint算法——本质上是牺牲最高位作为标识数据结束位,达到变长编码,说白了就是贪心的分割位