Get least sum of a combination of matrix elements

后端 未结 2 747
暖寄归人
暖寄归人 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 19:47

    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

提交回复
热议问题