当前位置:网站首页>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
总结
二维前缀和板子
边栏推荐
- 深入解析结构化异常处理(SEH) - by Matt Pietrek
- 批处理初识
- 96% of the collected traffic is prevented by bubble mart of cloud hosting
- Why use node
- 2020 Bioinformatics | TransformerCPI
- 2021 RSC | Drug–target affinity prediction using graph neural network and contact maps
- Lnk2038 detected a mismatch of "runtimelibrary": the value "md_dynamicrelease" does not match the value "mdd_dynamicdebug" (in main.obj)
- Keysight N9320B射频频谱分析仪解决轮胎压力监测方案
- Why is the probability of pod increasing after IPtable
- 多位科技公司创始人向Entrepreneur First提供高达1.58亿美元的C轮融资,协助其投资下一代全球创新者
猜你喜欢
2020 Bioinformatics | TransformerCPI
96% of the collected traffic is prevented by bubble mart of cloud hosting
leetcode刷题:二叉树07(二叉树的最大深度)
Flink learning 8: data consistency
dried food! Generation of rare samples based on GaN
Exercises in quantum mechanics
旭化成首次参展第五届中国国际进口博览会(5th CIIE)
leetcode刷题:二叉树04(二叉树的层序遍历)
分布式系统:what、why、how
毕业设计:设计秒杀电商系统
随机推荐
dried food! Generation of rare samples based on GaN
Leetcode brush questions: binary tree 05 (flip binary tree)
Redis:集合Set类型数据的操作命令
MIN_RTO 对话
TCP-三次握手和四次挥手简单理解
[microservice openfeign] use openfeign to remotely call the file upload interface
2020 Bioinformatics | TransformerCPI
干货!基于GAN的稀有样本生成
[csrf-01] basic principle and attack and defense of Cross Site Request Forgery vulnerability
hbuildx中夜神模拟器的配置以及热更新
Parameterization of controls in katalon
毕业设计项目
Touch your hand and bring you a commonjs specification
Programmers' telecommuting is mixed | community essay solicitation
RHCSA 04 - 进程管理
Touch and take you to implement an EventEmitter
The difference between bagging and boosting in machine learning
Global exposure and roller shutter exposure of industrial cameras
2020 Bioinformatics | TransformerCPI
仿《游戏鸟》源码 手游发号评测开服开测合集专区游戏下载网站模板