当前位置:网站首页>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
总结
二维前缀和板子
边栏推荐
- 干货!基于GAN的稀有样本生成
- 2021 RSC | Drug–target affinity prediction using graph neural network and contact maps
- RHCSA 08 - automount配置
- 网络 - VXLAN
- 北漂程序员,月薪20K,一年攒15W,正常吗?
- 【微服务|openfeign】@FeignClient详解
- Distributed system: what, why, how
- Leetcode skimming: binary tree 09 (minimum depth of binary tree)
- 微信脑力比拼答题小程序_支持流量主带最新题库文件
- 架构实战营 - 第 6 期 模块九之毕业设计
猜你喜欢

Redis:哈希hash类型数据操作命令

Exercises in quantum mechanics

Leetcode skimming: binary tree 07 (maximum depth of binary tree)

96% of the collected traffic is prevented by bubble mart of cloud hosting

Emlog user registration plug-in is worth 80 yuan
![[Logitech] m720](/img/bb/44144a1c3907808398c05b3b36962c.png)
[Logitech] m720

一个漂亮的API文档生成工具

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

Idea configuration 360zip open by default -- external tools

Main applications of TDK lambda power supply
随机推荐
[microservice openfeign] @feignclient detailed explanation
Tcp- simple understanding of three handshakes and four waves
C语言单向链表练习
5张图告诉你:同样是职场人,差距怎么这么大?
新手找陪驾要注意什么
One click compilation and deployment of MySQL
ctf-pikachu-XSS
Understand the principle of bytecode enhancement technology through the jvm-sandbox source code
微信公众号无限回调授权系统源码
RHCSA 07 - 用户与群组管理
leetcode刷题:二叉树05(翻转二叉树)
Confession code collection, who says program apes don't understand romance
How to add custom API objects in kubernetes (1)
毕业设计:设计秒杀电商系统
Leetcode brush questions: binary tree 05 (flip binary tree)
Leader: who uses redis expired monitoring to close orders and get out of here!
Parameterization of controls in katalon
Distributed system: what, why, how
DP83848+网线热拔插
leetcode刷题:二叉树04(二叉树的层序遍历)