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])
相关推荐
现在,此刻6 小时前
leetcode 11. 盛最多水的容器 -java
java·算法·leetcode
☆璇7 小时前
【C++】哈希的应用:位图和布隆过滤器
算法·哈希算法
一株月见草哇9 小时前
Matlab(4)
人工智能·算法·matlab
hans汉斯9 小时前
基于深度学习的苹果品质智能检测算法研究
人工智能·深度学习·算法
火车叨位去19499 小时前
力扣top100(day01-05)--矩阵
算法·leetcode·矩阵
mit6.8249 小时前
[Robotics_py] 机器人运动模型 | `update`函数 | 微积分&矩阵
人工智能·python·算法
地平线开发者10 小时前
征程 6 | 自定义查表算子实现量化部署
算法·自动驾驶
冬夜戏雪11 小时前
java学习 leetcode 二分查找 图论
java·学习·leetcode
火车叨位去194912 小时前
力扣top100(day02-05)--二叉树 02
算法·leetcode·职场和发展
James. 常德 student12 小时前
leetcode-hot-100 (图论)
算法·leetcode·图论