'Dynamic programming min grid path
Hi I've started coding with dynamic programming, but I always get the error ''int' object is not subscriptable'. I've searched online, but I don't even put an int function in my code. Could someone help please?
def minCost(cost, row, col):
# For 1st column
for i in range(1, row):
cost[i][0] += cost[i - 1][0]
# For 1st row
for j in range(1, col):
cost[0][j] += cost[0][j - 1]
# For rest of the 2d matrix
for i in range(1, row):
for j in range(1, col):
cost[i][j] += (min(cost[i - 1][j - 1],
min(cost[i - 1][j],
cost[i][j - 1])))
# Returning the value in
# last cell
return cost[row - 1][col - 1]
Solution 1:[1]
I do not understand which number is supposed to be what in your example but when I copy you function and put these in it as parameters I get an output of 10.
cost = [[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
rows = 4
col = 4
print(minCost(cost,rows,col))
OUTPUT : 10
Please maybe elaborate further and make sure your parameters are in the correct format.
EDIT: also in your example, the matrix you provided and the rows and cols, they dont match. So I do not understand what those parameters represent
Solution 2:[2]
You are trying to index cost in a dimension that doesn't exist. It needs to be 2 dimensional to have 2 indexes:
[[1, 2, 3],
[1, 2, 3],
[1, 2, 3]]
You must pass cost as the matrix, not row.
# In this form
minCost([1, 2, 3], [1, 2, 3], [1, 2, 3]], 2, 3)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Josip Juros |
| Solution 2 | Freddy Mcloughlan |
