Leetcode 3070. Count Submatrices with Top-Left Element and Sum Less Than k

Problem

You are given a 0-indexed integer matrix grid and an integer k.

Return the number of submatrices that contain the top-left element of the grid, and have a sum less than or equal to k.

Algorithm

Dynamic programming (DP): let f[i][j] be the sum of the submatrix from (0,0) to (i,j), and count all positions where f[i][j] ≤ k.

Code

python3 复制代码
class Solution:
    def countSubmatrices(self, grid: List[List[int]], k: int) -> int:
        m, n, ans = len(grid), len(grid[0]), 0
        for i in range(m):
            for j in range(n):
                if i > 0:
                    grid[i][j] += grid[i-1][j]
                if j > 0:
                    grid[i][j] += grid[i][j-1]
                if i > 0 and j > 0:
                    grid[i][j] -= grid[i-1][j-1]
                if grid[i][j] <= k:
                    ans += 1
        
        return ans
相关推荐
BirdenT2 小时前
20260519紫题训练
c++·算法
csdn_aspnet8 小时前
C语言 Lomuto分区算法(Lomuto Partition Algorithm)
c语言·开发语言·算法
谙弆悕博士8 小时前
【附C源码】从零实现C语言堆数据结构:原理、实现与应用
c语言·数据结构·算法··数据结构与算法
gaosushexiangji11 小时前
DIC系统推荐:基于千眼狼三维数字图像相关的无人机旋翼疲劳试验全场应变与位移测量
人工智能·算法
小王C语言13 小时前
【线程概念与控制】:线程封装
jvm·c++·算法
圣保罗的大教堂13 小时前
leetcode 796. 旋转字符串 简单
leetcode
kyle~13 小时前
工程数学---点云配准卡布施(Kabsch)算法(求解最优旋转矩阵)
线性代数·算法·矩阵
张二娃同学13 小时前
03_变量常量与输入输出_printf与scanf详解
算法
江南十四行14 小时前
并发编程(一)
java·jvm·算法
z2005093014 小时前
今日算法(依旧二叉树)
算法·leetcode·职场和发展