Leetcode 931. Minimum Falling Path Sum

Problem

Given an n x n array of integers matrix, return the minimum sum of any falling path through matrix.

A falling path starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position (row, col) will be (row + 1, col - 1), (row + 1, col), or (row + 1, col + 1).

Algorithm

Dynamic Programming (DP). Define the state dpij as the minimum falling path to the point at (i-row, j-column). dpij = min(dpi-1j-1, dpi-1j, dpi-1j+1) + matrixij.

Code

python3 复制代码
class Solution:
    def minFallingPathSum(self, matrix: List[List[int]]) -> int:
        r_size = len(matrix)
        if r_size == 1:
            return min(matrix[0])
        c_size = len(matrix[0])
        
        minSum = [[0] * c_size for r in range(r_size+1)]
        for r in range(1, r_size+1):
            print(r)
            for c in range(c_size):
                minSum[r][c] = minSum[r-1][c] + matrix[r-1][c]
                if c > 0 and minSum[r][c] > minSum[r-1][c-1] + matrix[r-1][c]:
                    minSum[r][c] = minSum[r-1][c-1] + matrix[r-1][c]
                if c < c_size-1 and minSum[r][c] > minSum[r-1][c+1] + matrix[r-1][c]:
                    minSum[r][c] = minSum[r-1][c+1] + matrix[r-1][c]
        
        return min(minSum[r_size])
相关推荐
颜挺锐25 分钟前
如何轻松通过性能测试面试之第十一篇:如何判断应用的最大处理能力
面试·职场和发展
DeepAgent1 小时前
AI Agent 面试篇(01):AI 岗位面试到底怎么走——从网申到 Offer 的完整流程
人工智能·面试·职场和发展
CodeRecycle1 小时前
Python 自动配置 pip 支持库(通过 Windows Bat 脚本)
算法
liliangcsdn1 小时前
特质偏度因子的计算示例和分析
算法
荆棘鸟智能2 小时前
无人机遥感图像实时拼接算法工程实践:从特征提取到全景融合的完整技术链路
算法·无人机
6Hzlia2 小时前
【Classic 150 刷题计划】 LeetCode 58. 最后一个单词的长度 | C++ 极简反向遍历与单变量状态机
算法
AgentMaster3 小时前
企业如何应用智能客服?5 个典型场景的技术架构与实施路径
大数据·算法
程曦曦3 小时前
MySQL 生产库误删 98 张表后的时间点恢复实战:从 binlog 解析到资金对账
linux·数据结构·其他·算法·ubuntu·运维开发
weixin_307779134 小时前
C++代码实现MATLAB中的ode45函数功能
开发语言·c++·算法·matlab
不穿鞋的懒羊羊4 小时前
dfs深度优先搜索
算法