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])
相关推荐
BHXDML21 小时前
第五章:支持向量机
算法·机器学习·支持向量机
2401_8414956421 小时前
具身智能:从理论到现实,人工智能的下一场革命
人工智能·算法·机器人·硬件·具身智能·通用智能·专用智能
Felven21 小时前
B. MEXor Mixup
算法
阿崽meitoufa21 小时前
JVM虚拟机:垃圾收集算法
java·jvm·算法
练习时长一年1 天前
LeetCode热题100(分割等和子集)
算法·leetcode·职场和发展
52Hz1181 天前
力扣148.排序链表
leetcode
七号驿栈1 天前
07_汽车信息安全算法在线验证工具(测试报告)
算法
啦哈拉哈1 天前
【Python】知识点零碎学习4
python·学习·算法
iAkuya1 天前
(leetcode)力扣100 46二叉树展开为链表(递归||迭代||右子树的前置节点)
windows·leetcode·链表
爱喝可乐的老王1 天前
线性回归模型案例:广告投放效果预测
算法·回归·线性回归