dp
with the same dimensions as grid
and fill the last row of dp
with the values of the last row of grid
.(i, j)
, iterate over all columns k
of the next row.
b. Calculate the cost to move from (i, j)
to (i+1, k)
as grid[i][j] + moveCost[grid[i][j]][k] + dp[i+1][k]
.
c. Update dp[i][j]
with the minimum cost calculated.dp
array, the first row will contain the minimum costs to reach the last row starting from each cell in the first row.dp
.