Get least sum of a combination of matrix elements

后端 未结 2 724
暖寄归人
暖寄归人 2021-01-18 19:01

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

2条回答
  •  情歌与酒
    2021-01-18 20:02

    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]
    

提交回复
热议问题