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])
相关推荐
白白白小纯3 分钟前
每日算法day3—回文链表,链表分割
c语言·数据结构·算法·leetcode
城管不管21 分钟前
RabbitMQ死信队列
java·分布式·ai·面试·职场和发展·rabbitmq·agent
手写码匠27 分钟前
华为云Flexus+DeepSeek征文|Dify 构建企业级联网搜索 Agent:查询改写、多源检索与引用溯源实战
人工智能·深度学习·算法·aigc
七夜zippoe30 分钟前
DolphinDB 能耗统计分析实战:报表生成、同比环比与定额对比
人工智能·算法·dolphindb·报表生成·能耗统计·定额对比
软件测试媛33 分钟前
软件测试面试问题汇总
功能测试·面试·职场和发展·压力测试
城管不管39 分钟前
rabbitmq如何保证消息不丢失?解决方案又是什么?
开发语言·ai·面试·职场和发展·rabbitmq·php·agent
为啥全要学40 分钟前
在大语言模型上使用 PPO 算法
人工智能·算法·语言模型
zander2581 小时前
35. 搜索插入位置:从边界语义理解二分查找
数据结构·算法·leetcode
汤愈韬1 小时前
模型求解算法
人工智能·算法·机器学习
Keven_112 小时前
算法札记:DP中的滚动数组
算法·滚动数组