题解 | #矩阵的最小路径和#
矩阵的最小路径和
https://www.nowcoder.com/practice/7d21b6be4c6b429bb92d219341c4f8bb
class Solution: def minPathSum(self, matrix: List[List[int]]) -> int: if not matrix or not matrix[0]: return 0 n, m = len(matrix), 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]