当前位置:网站首页>leetcode:1314. 矩阵区域和【二维前缀和模板】
leetcode:1314. 矩阵区域和【二维前缀和模板】
2022-07-04 03:53:00 【白速龙王的回眸】

分析
二维前缀和模板
dp的时候多一行一列记录0方便统一式子
ac code
class Solution:
def matrixBlockSum(self, mat: List[List[int]], k: int) -> List[List[int]]:
# 二维前缀和
m, n = len(mat), len(mat[0])
# row and col 补充一行全0
dp = [[0] * (n + 1) for _ in range(m + 1)]
dp[1][1] = mat[0][0]
for j in range(2, n + 1):
dp[1][j] = mat[0][j - 1] + dp[1][j - 1]
for i in range(2, m + 1):
dp[i][1] = mat[i - 1][0] + dp[i - 1][1]
for i in range(2, m + 1):
for j in range(2, n + 1):
#print(i, j)
dp[i][j] = mat[i - 1][j - 1] + dp[i - 1][j] + dp[i][j - 1] - dp[i - 1][j - 1]
#print(dp)
res = [[0] * n for _ in range(m)]
for i in range(1, m + 1):
for j in range(1, n + 1):
left, right = max(i - k, 1), min(m, i + k)
up, down = max(j - k, 1), min(n, j + k)
res[i - 1][j - 1] = dp[right][down] + dp[left - 1][up - 1] - dp[left - 1][down] - dp[right][up - 1]
return res
总结
二维前缀和板子
边栏推荐
- 博朗与Virgil Abloh于2021年为纪念博朗品牌100周年而联合打造的“功能性艺术”将在博物馆展出Abloh作品期间首次亮相
- (指针)编写函数void fun(int x,int *pp,int *n)
- leetcode刷题:二叉树08(N叉树的最大深度)
- Pytest基础自学系列(一)
- I Build a simple microservice project
- Confession code collection, who says program apes don't understand romance
- 批处理初识
- [microservice openfeign] @feignclient detailed explanation
- Tcp- simple understanding of three handshakes and four waves
- Redis:哈希hash类型数据操作命令
猜你喜欢

Distributed system: what, why, how

Ppt tutorial, how to save a presentation as a PDF file in PowerPoint?

Flink learning 6: programming model

leetcode刷题:二叉树08(N叉树的最大深度)

The difference between bagging and boosting in machine learning

UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0x98 in position 1093: illegal multibyte sequence

什么是上下文?

【愚公系列】2022年7月 Go教学课程 002-Go语言环境安装

R语言中如何查看已安装的R包

架构训练毕业设计+总结
随机推荐
I was tortured by my colleague's null pointer for a long time, and finally learned how to deal with null pointer
leetcode刷题:二叉树07(二叉树的最大深度)
[microservice openfeign] use openfeign to remotely call the file upload interface
y55.第三章 Kubernetes从入门到精通 -- HPA控制器及metrics-server(二八)
毕业设计:设计秒杀电商系统
Common methods of threads
leetcode 121 Best Time to Buy and Sell Stock 买卖股票的最佳时机(简单)
5张图告诉你:同样是职场人,差距怎么这么大?
【愚公系列】2022年7月 Go教学课程 001-Go语言前提简介
RHCSA 06 - suid, sgid, sticky bit(待补充)
[webrtc] M98 Ninja build and compile instructions
干货!基于GAN的稀有样本生成
Redis cluster view the slots of each node
Main applications of TDK lambda power supply
RHCSA 08 - automount配置
Global exposure and roller shutter exposure of industrial cameras
2021 RSC | Drug–target affinity prediction using graph neural network and contact maps
01 QEMU starts the compiled image vfs: unable to mount root FS on unknown block (0,0)
JS实现文字滚动 跑马灯效果
C语言双向链表初版