47-Maximum value of gifts-python

Problem: There is a gift in each square of an m*n chessboard, and each gift has a certain value (value greater than 0). You can start from the upper left corner of the board to get the gifts in the grid, and move to the right or down one square at a time, until you reach the lower right corner of the board. Given a chessboard and the gifts on it, please calculate the maximum value of gifts you can get?

def get_max_value(m_n):
    rows = len(m_n)
    cols = len(m_n[1])
    # 注意这种初始化列表的方式
    res = [[0 for i in range(cols)] for j in range(rows)]

    i=0
    while i<cols:
        j= 0
        while j<rows:
            if i == 0 and j ==0:
                arr = m_n[0][0]

            elif  i ==0 and j!=0:
                arr = res[0][j-1]+m_n[0][j]
            elif j ==0 and i != 0:
                arr = res[i-1][0] + m_n[i][0]
            else:
                arr = max([res[i-1][j],res[i][j-1]]) + m_n[i][j]

            res[i][j] = arr

            j += 1
        i += 1
    return res

  Note: Using the idea of ​​dynamic programming, the state equation is: f(i,j)=max(f(i-1,j),f(i,j-1))+values(i,j). If it is in the first row, the maximum value up to the current grid is the maximum value of the previous grid + the value of the current grid; if it is in the first column, the same is true. The maximum value of the grid in the lower right corner is the maximum value required for this question.

Guess you like

Origin blog.csdn.net/wh672843916/article/details/105503738