Question: The instructor posted a code in the Code section : Dynamic Programming Example ( ChatGPT ) To change the above Python code to C +

The instructor posted a code in the Code section :
Dynamic Programming Example (ChatGPT)
To change the above Python code to C++.(Hint: use the global variable for the array. Or try "int ** array" for the two-D arrays)
code:
def minPathSum(grid):
# Get the number of rows (m) and columns (n)
m, n = len(grid), len(grid[0])
# Initialize a 2D DP array with the same size as the grid
dp =[[0]* n for _ in range(m)]
# Base case: the top-left corner is the starting point
dp[0][0]= grid[0][0]
# Fill the first row (can only move right)
for j in range(1, n):
dp[0][j]= dp[0][j -1]+ grid[0][j]
# Fill the first column (can only move down)
for i in range(1, m):
dp[i][0]= dp[i -1][0]+ grid[i][0]
# Fill the rest of the DP table
for i in range(1, m):
for j in range(1, n):
dp[i][j]= min(dp[i -1][j], dp[i][j -1])+ grid[i][j]
# The bottom-right corner will have the minimum path sum
return dp[m -1][n -1]
# Example usage:
grid =[[1,3,1],
[1,5,1],
[4,2,1]]
print(minPathSum(grid))# Output: 7

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!