【DP】931. Minimum Falling Path Sum

Subject description:

Given a square array of integers A, we want the minimum sum of a falling path through A.

A falling path starts at any element in the first row, and chooses one element from each row. The next row's choice must be in a column that is different from the previous row's column by at most one.

Example 1:
Input: [[1,2,3],[4,5,6],[7,8,9]]
Output: 12
Explanation: 
The possible falling paths are:
[1,4,7], [1,4,8], [1,5,7], [1,5,8], [1,5,9]
[2,4,7], [2,4,8], [2,5,7], [2,5,8], [2,5,9], [2,6,8], [2,6,9]
[3,5,7], [3,5,8], [3,5,9], [3,6,8], [3,6,9]
The falling path with the smallest sum is [1,4,7], so the answer is 12.
Note:
1 <= A.length == A[0].length <= 100
-100 <= A[i][j] <= 100

Problem-solving ideas:

This question is seeking the minimum and descending path, i.e., positions (row, col) to reach a position (row + 1, col-1), (row + 1, col), (row + 1, col + 1).

Obviously this is a dynamic programming problem. With dp [row] [col] represents the arrival position (row, col) and the minimum accumulated, it is the current position is calculated A [row] [col] plus (row-1, col-1 ), (row-1 minimum of three positions, COL), and (. 1-Row, + COL. 1) , namely:
dp[row][col] = A[row][col] + min(dp[row-1][col-1], dp[row-1][col], dp[row-1][col+1])
Thus, we only need to traverse the matrix from top to bottom, the minimum value of the update accumulation at each position. Finally, dp last line of the minimum is the final answer.

Note: In the programming time to initialize the first row dp[0] = A[0], while traversing each row should pay attention to the leftmost and rightmost position of the boundary conditions.

Python3 achieve:

class Solution:
    def minFallingPathSum(self, A: List[List[int]]) -> int:
        lens = len(A)
        dp = [[0] * lens for _ in range(lens)]
        dp[0] = A[0]  # 初始化第一行
        for row in range(1, lens):
            dp[row][0] = A[row][0] + min(dp[row-1][0], dp[row-1][1])
            for col in range(1, lens-1):
                dp[row][col] = A[row][col] + min(dp[row-1][col-1], dp[row-1][col], dp[row-1][col+1])
            dp[row][lens-1] = A[row][lens-1] + min(dp[row-1][lens-2], dp[row-1][lens-1])
        return min(dp[-1])

Reproduced in: https: //www.jianshu.com/p/13167c3c5801

Guess you like

Origin blog.csdn.net/weixin_34387284/article/details/91203967