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 dp[i][j] as the minimum falling path to the point at (i-row, j-column). dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i-1][j+1]) + matrix[i][j].

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])
相关推荐
We་ct2 小时前
LeetCode 5. 最长回文子串:DP + 中心扩展
前端·javascript·算法·leetcode·typescript
王老师青少年编程6 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【哈夫曼贪心】:合并果子
c++·算法·贪心·csp·信奥赛·哈夫曼贪心·合并果子
叼烟扛炮7 小时前
C++第二讲:类和对象(上)
数据结构·c++·算法·类和对象·struct·实例化
天疆说7 小时前
【哈密顿力学】深入解读航天器交会最优控制中的Hamilton函数
人工智能·算法·机器学习
wuweijianlove8 小时前
关于算法设计中的代价函数优化与约束求解的技术7
算法
小程故事多_808 小时前
[大模型面试系列] 多轮对话 Agent 设计实战(含窗口优化 + 工具调用精髓)
人工智能·面试·职场和发展
leoufung8 小时前
LeetCode 149: Max Points on a Line - 解题思路详解
算法·leetcode·职场和发展
样例过了就是过了8 小时前
LeetCode热题100 最长公共子序列
c++·算法·leetcode·动态规划
HXDGCL8 小时前
矩形环形导轨:自动化循环线的核心运动单元解析
运维·算法·自动化
谭欣辰9 小时前
C++ 排列组合完整指南
开发语言·c++·算法