# LeetCode 931. 下降路径最小和

·  阅读 1609

## 题目地址(931. 下降路径最小和)

leetcode-cn.com/problems/mi…

## 题目描述



[[2,1,3],      [[2,1,3],
[6,5,4],       [6,5,4],
[7,8,9]]       [7,8,9]]

[[-19,57],
[-40,-5]]



n == matrix.length n == matrix[i].length 1 <= n <= 100 -100 <= matrix[i][j] <= 100

## 思路

DP规划，存储【-1】数组的min内容，然后根据不同特殊条件进行遍历

## 代码

• 语言支持：Python3

Python3 Code:


class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
length = len(matrix)
# 构建DP矩阵进行记录
dp =  [[0]*length for i in range(length)]
dp[0] = matrix[0]
for i in range(1,length):
for j in range(length):
val = 0
##设置边界条件的特殊性
if j == 0:
val = min(dp[i-1][j],dp[i-1][j+1])
elif j == length-1:
val = min(dp[i - 1][j], dp[i - 1][j - 1])
else:
val = min(dp[i - 1][j-1],dp[i - 1][j], dp[i - 1][j + 1])
dp[i][j] = val+matrix[i][j]
return min(dp[-1])

if __name__ == '__main__':
matrix = [[2,1,3],[6,5,4],[7,8,9]]
matrix = [[-19, 57], [-40, -5]]
res = Solution().minFallingPathSum(matrix)
print(res)



• 时间复杂度：$O(n^2)$
• 空间复杂度：$O(n^2)$