📅  最后修改于: 2023-12-03 15:12:39.718000             🧑  作者: Mango
This question is based on dynamic programming.
Given a 2D matrix of positive integers, find a path from the top left corner to the bottom right corner with maximum sum of all the paths.
Consider a 3x3 matrix:
1 2 3
4 5 6
7 8 9
The maximum sum path is 1 -> 4 -> 7 -> 8 -> 9
, with a sum of 29
.
This problem can be solved using dynamic programming. We can define a dp
array where each element dp[i][j]
represents the maximum sum path from the top left corner to (i, j)
.
The base case is the top left corner, where dp[0][0] = matrix[0][0]
. For the first row and first column, we can only come from the previous element, so dp[i][0] = dp[i-1][0] + matrix[i][0]
and dp[0][j] = dp[0][j-1] + matrix[0][j]
.
For all other elements, we can come from either above or left, so dp[i][j] = max(dp[i-1][j], dp[i][j-1]) + matrix[i][j]
.
At the end, the maximum sum path can be obtained from dp[m-1][n-1]
, where m
is the number of rows and n
is the number of columns in the matrix.
def max_sum_path(matrix):
m, n = len(matrix), len(matrix[0])
dp = [[0] * n for _ in range(m)]
dp[0][0] = matrix[0][0]
# initialize first row and first column
for i in range(1, m):
dp[i][0] = dp[i-1][0] + matrix[i][0]
for j in range(1, n):
dp[0][j] = dp[0][j-1] + matrix[0][j]
# fill in the rest of the dp array
for i in range(1, m):
for j in range(1, n):
dp[i][j] = max(dp[i-1][j], dp[i][j-1]) + matrix[i][j]
# return maximum sum path
return dp[m-1][n-1]
The time complexity of this solution is O(mn)
, where m
is the number of rows and n
is the number of columns in the matrix.
The space complexity of this solution is also O(mn)
, as we are creating a dp
array of size m x n
.