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

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])

相关推荐

  1. Leetcode 931. Minimum Falling Path Sum

    2024-04-26 00:42:03       37 阅读
  2. LeetCode 981, 219, 78

    2024-04-26 00:42:03       29 阅读
  3. LeetCode //C - 933. Number of Recent Calls

    2024-04-26 00:42:03       57 阅读
  4. LeetCode //C - 901. Online Stock Span

    2024-04-26 00:42:03       56 阅读
  5. LeetCode938. Range Sum of BST

    2024-04-26 00:42:03       29 阅读
  6. leetcode93. 复原 IP 地址

    2024-04-26 00:42:03       49 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-26 00:42:03       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-26 00:42:03       106 阅读
  3. 在Django里面运行非项目文件

    2024-04-26 00:42:03       87 阅读
  4. Python语言-面向对象

    2024-04-26 00:42:03       96 阅读

热门阅读

  1. go | 切片的长度和容量

    2024-04-26 00:42:03       34 阅读
  2. MySQL数据库管理DDL语言和数据库管理

    2024-04-26 00:42:03       34 阅读
  3. vue3中a-select的模糊查询

    2024-04-26 00:42:03       36 阅读
  4. 蚂蚁 2025届暑期实习 多模态LLM 面经

    2024-04-26 00:42:03       35 阅读
  5. Linux第三章

    2024-04-26 00:42:03       30 阅读
  6. 智能合约语言(eDSL)—— 并行化方案

    2024-04-26 00:42:03       28 阅读
  7. Leetcode 150:逆波兰表达式求值

    2024-04-26 00:42:03       30 阅读