Yesterday one of my friend came with a problem, asking me to find the solution.
The problem
I have a matrix(n x m)
. I need to
It seems that you can go only in right and down directions. For this case (otherwise use path finding algorithms) note that you can come in every cell either from upper cell or from left cell. The cheapest path to this cell will be minimum from these values. So DP solution may look like (pseudocode):
see corrections here
Cost[0, 0] = matrix[0, 0]
for x = 1 to cols - 1
Cost[0, x] = matrix[0, x] + Cost[0, x-1] //0th row
for y = 1 to rows - 1
Cost[y, 0] = matrix[y, 0] + Cost[y-1, 0] //0th column
//proper filling of 0th row and 0th column
for y = 1 to rows - 1
for x = 1 to cols - 1
Cost[y, x] = matrix[y, x] + Min(Cost[y-1, x], Cost[y, x-1])
then Cost[n-1, n-1] is what you need
An update to MBo's answer. Given a n*m (n=3, m=4 in your post) The space consumed can be reduce to O(N) by only remembering the result for previous line (column).
Cost[0] = matrix[0, 0]
for x = 1 to m - 1
Cost[x] = matrix[0, x] + Cost[x-1]
for y = 1 to n - 1
Cost[0] += matrix[y, 0]
for x = 1 to m - 1
Cost[x] = matrix[y, x] + Min(Cost[x-1], Cost[x])
output(Cost[n-1])
Don't know how to write in PHP... Here's python sample code
matrix = [
[3, 44, 75],
[21, 98, 60],
]
n = len(matrix)
m = len(matrix[0])
cost = [0] * m
cost[0] = matrix[0][0]
for x in xrange(1, m):
cost[x] = matrix[0][x] + cost[x-1]
for y in xrange(1, n):
cost[0] += matrix[y][0]
for x in xrange(1, m):
cost[x] = matrix[y][x] + min(cost[x-1], cost[x])
print cost[-1]