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])
相关推荐
折哥的程序人生 · 物流技术专研4 小时前
Java面试85题图解版 · 特别篇:2026后端高频面试题复盘(算法底层逻辑+高并发架构设计全解析,附Java实战代码)
java·网络·数据库·算法·面试
想吃火锅10055 小时前
【leetcode】14.最长公共前缀js
算法·leetcode·职场和发展
云絮.6 小时前
数据库操作
数据库·mysql·算法·oracle
小林ixn6 小时前
LeetCode 206. 反转链表(迭代 + 递归详解)
算法·leetcode·链表
凡人叶枫7 小时前
Effective C++ 条款17:以独立语句将 newed 对象置入智能指针
java·linux·开发语言·c++·算法
我爱cope8 小时前
【Agent智能体26 | 多智能体-多智能体工作流】
人工智能·设计模式·语言模型·职场和发展
菜鸟‍8 小时前
LeetCode 1 27 和 704 || 两数之和 移除元素 二分查找
算法·leetcode·职场和发展
退休倒计时9 小时前
【每日一题】LeetCode 142. 环形链表 II TypeScript
算法·leetcode·链表·typescript
popcorn_min9 小时前
Digits 手写数字识别:随机森林多分类 + 像素级特征热力图
算法·随机森林·分类
liulilittle10 小时前
拥塞控制:排水终止的两种决策:OR 与 AND
网络·tcp/ip·计算机网络·算法·信息与通信·tcp·通信