I have to implement some functions in python to find the minimum cost in a matrix.We must go down or right and to an adjacent number so at each step we have only two possible choices.
i wrote the fisrt version (naive one) which works:
def minimal_trajectorry_helper(matrix, m, n):
if ( (n > len(matrix) -1 ) or (m > len(matrix) -1)):
return 1000000000
elif ((m == len(matrix) - 1) and (n == len(matrix) - 1)):
return matrix[m][n]
else:
result = matrix[m][n] + min(minimal_trajectorry_helper(matrix, m+1, n),
minimal_trajectorry_helper(matrix, m, n+1) )
return result
But when i want to optimize it using memoization i can't find the right answer. I tried different ways but i wasn't able to do it correctly. Here is what i wrote:
def dptd_minimal_trajectorry_helper(matrix, m, n, track):
if ( (n > len(matrix) -1 ) or (m > len(matrix) -1)):
return 1000000000
elif ((m == len(matrix) - 1) and (n == len(matrix) - 1)):
return matrix[m][n]
elif (track[m][n] != -1):
return track[m][n]
else:
result = matrix[m][n] + min(dptd_minimal_trajectorry_helper(matrix, m+1, n, track),
dptd_minimal_trajectorry_helper(matrix, m, n+1, track)
track[m][n] = result
return result
Here is an example :
[2,3,1,1,6]
[1,4,4,1,4]
[7,1,2,2,5]
[2,1,3,8,3]
[2,4,3,2,1]
The naive version gives me the right anwser which is 18 -> 2,1,4,1,1,3,3,2,1 But the second one gives me 12
Thanks in advance for any help :)
EDIT : I call the naive version like minimal_trajectorry_helper(matrix, 0, 0) and the optimized one like dptd_minimal_trajectorry_helper(matrix, m, n, track) where track is initialized by : track = [[-1]*5]*5