题解 | #矩阵的最小路径和#
矩阵的最小路径和
https://www.nowcoder.com/practice/7d21b6be4c6b429bb92d219341c4f8bb
先算出第一行和第一列各个位置的路径之和
class Solution:
def minPathSum(self , matrix: List[List[int]]) -> int:
# write code here
n = len(matrix)#行
m = len(matrix[0])#列
dp = [[0]*m for _ in range(n)]
dp[0][0] = matrix[0][0]
for j in range(1,m):
dp[0][j] = dp[0][j-1]+matrix[0][j]
for i in range(1,n):
dp[i][0] = dp[i-1][0]+matrix[i][0]
for i in range(1,n):
for j in range(1,m):
dp[i][j] = min(dp[i-1][j],dp[i][j-1])+matrix[i][j]
return dp[-1][-1]