class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
def dfs(r, c):
if r == len(grid) - 1 and c == len(grid[0]) - 1:
return grid[r][c]
if r == len(grid) or c == len(grid[0]):
return float('inf')
return grid[r][c] + min(dfs(r + 1, c), dfs(r, c + 1))
return dfs(0, 0)Where is the number of rows and is the number of columns.
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
dp = [[-1] * n for _ in range(m)]
def dfs(r, c):
if r == m - 1 and c == n - 1:
return grid[r][c]
if r == m or c == n:
return float('inf')
if dp[r][c] != -1:
return dp[r][c]
dp[r][c] = grid[r][c] + min(dfs(r + 1, c), dfs(r, c + 1))
return dp[r][c]
return dfs(0, 0)Where is the number of rows and is the number of columns.
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
ROWS, COLS = len(grid), len(grid[0])
dp = [[float("inf")] * (COLS + 1) for _ in range(ROWS + 1)]
dp[ROWS - 1][COLS] = 0
for r in range(ROWS - 1, -1, -1):
for c in range(COLS - 1, -1, -1):
dp[r][c] = grid[r][c] + min(dp[r + 1][c], dp[r][c + 1])
return dp[0][0]Where is the number of rows and is the number of columns.
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
ROWS, COLS = len(grid), len(grid[0])
dp = [float("inf")] * (COLS + 1)
dp[COLS - 1] = 0
for r in range(ROWS - 1, -1, -1):
for c in range(COLS - 1, -1, -1):
dp[c] = grid[r][c] + min(dp[c], dp[c + 1])
return dp[0]Where is the number of rows and is the number of columns.