class Solution:
#参数grid: 二维整数数组
#返回值: 一个整数,使其路径上的所有数字之和最小化
def minPathSum(self, grid):
for i in range(len(grid)):
for j in range(len(grid[0])):
if i == 0 and j > 0:
grid[i][j] += grid[i][j-1]
elif j == 0 and i > 0:
grid[i][j] += grid[i-1][j]
elif i > 0 and j > 0:
grid[i][j] += min(grid[i-1][j], grid[i][j-1])
return grid[len(grid) - 1][len(grid[0]) - 1]
#主函数
if name == ‘main’:
solution = Solution()
grid = [[1,3,1],[1,5,1],[4,2,1]]
length = solution.minPathSum(grid)
print(“输入:”, grid)
print(“输出:”, length)
最小路径和
最新推荐文章于 2024-11-08 13:43:44 发布