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])
相关推荐
Trent19851 小时前
影楼精修-肤色统一算法解析
图像处理·人工智能·算法·计算机视觉
feifeigo1231 小时前
高光谱遥感图像处理之数据分类的fcm算法
图像处理·算法·分类
a东方青2 小时前
蓝桥杯 2024 C++国 B最小字符串
c++·职场和发展·蓝桥杯
北上ing2 小时前
算法练习:19.JZ29 顺时针打印矩阵
算法·leetcode·矩阵
.格子衫.4 小时前
真题卷001——算法备赛
算法
XiaoyaoCarter4 小时前
每日一道leetcode
c++·算法·leetcode·职场和发展·二分查找·深度优先·前缀树
Hygge-star4 小时前
【数据结构】二分查找5.12
java·数据结构·程序人生·算法·学习方法
June`5 小时前
专题二:二叉树的深度搜索(二叉树剪枝)
c++·算法·深度优先·剪枝
好吃的肘子7 小时前
Elasticsearch架构原理
开发语言·算法·elasticsearch·架构·jenkins
胡耀超7 小时前
霍夫圆变换全面解析(OpenCV)
人工智能·python·opencv·算法·计算机视觉·数据挖掘·数据安全