Update to MBo . Considering that n * m (n = 3, m = 4 in your message) The consumed space can be reduced to O (N) only by remembering the result for the previous row (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])
I don't know how to write in PHP ... Here is an example python 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]
source share