25-cxsj-final/backend/problems/min_path_sum/solvers.py

57 lines
1.5 KiB
Python

from typing import List
def solve_dp(grid: List[List[int]]) -> int:
"""
Dynamic Programming solution for Minimum Path Sum.
O(M * N)
"""
if not grid or not grid[0]:
return 0
rows, cols = len(grid), len(grid[0])
dp = [[0] * cols for _ in range(rows)]
dp[0][0] = grid[0][0]
# Initialize first row
for j in range(1, cols):
dp[0][j] = dp[0][j-1] + grid[0][j]
# Initialize first column
for i in range(1, rows):
dp[i][0] = dp[i-1][0] + grid[i][0]
# Fill the rest
for i in range(1, rows):
for j in range(1, cols):
dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j]
return dp[rows-1][cols-1]
def solve_recursion(grid: List[List[int]]) -> int:
"""
Recursive Brute Force solution (Top-Down without Memoization).
O(2^(M+N))
Only for very small inputs!
"""
if not grid or not grid[0]:
return 0
rows, cols = len(grid), len(grid[0])
# Safety check to prevent freezing/recursion depth errors on large inputs if called accidentally
if rows + cols > 18:
# Fallback to DP for safety if input is too large for naive recursion
return solve_dp(grid)
def helper(r, c):
if r == 0 and c == 0:
return grid[0][0]
if r < 0 or c < 0:
return float('inf')
return grid[r][c] + min(helper(r-1, c), helper(r, c-1))
return helper(rows-1, cols-1)