To solve a common grid problem like finding the maximum path sum from the top-left to bottom-right corner (moving only right or down), here's a step-by-step approach using dynamic programming:
Problem Assumption
Given a 2D grid of non-negative integers, find the path from the top-left to bottom-right that maximizes the sum of the numbers along the path.
Approach
- Dynamic Programming (DP) Table: Create a DP table
dpwheredp[i][j]represents the maximum sum to reach cell(i,j). - Base Cases:
- The first row: Sum of all previous cells in the row (only right moves allowed).
- The first column: Sum of all previous cells in the column (only down moves allowed).
- Recurrence Relation: For any cell
(i,j)(not in first row/column), the maximum sum is the current cell value plus the maximum of the sum from the cell above (dp[i-1][j]) or the cell to the left (dp[i][j-1]). - Result: The value at
dp[m-1][n-1](bottom-right corner) gives the maximum path sum.
Solution Code
def max_path_sum(grid):
if not grid or not grid[0]:
return 0
m, n = len(grid), len(grid[0])
dp = [[0] * n for _ in range(m)]
# Base case: first cell
dp[0][0] = grid[0][0]
# Fill first row
for j in range(1, n):
dp[0][j] = dp[0][j-1] + grid[0][j]
# Fill first column
for i in range(1, m):
dp[i][0] = dp[i-1][0] + grid[i][0]
# Fill rest of the grid
for i in range(1, m):
for j in range(1, n):
dp[i][j] = grid[i][j] + max(dp[i-1][j], dp[i][j-1])
return dp[-1][-1]
Example Usage
For the grid:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
The maximum path sum is 12 (path: 1→3→5→2→1).
Note
If your problem is different (e.g., minimum path sum, number of paths with obstacles), please provide more details about the image/content, and I can adjust the solution accordingly!
Let me know if you need further clarification.


作者声明:本文包含人工智能生成内容。