Original link: https://leetcode.com/problems/minimum-falling-path-sum/
For elements in the second line and below, we can search the upper two or three elements and add the minimum value.
Boundary condition: elements in the most left and the most right. They can only search for two elements.
Code:
class Solution(object):
def minFallingPathSum(self, A):
"""
:type A: List[List[int]]
:rtype: int
"""
for r in range(1, len(A)):
A[r][0] += min(A[r-1][0], A[r-1][1])
for c in range(1, len(A[r]) - 1):
A[r][c] += min(A[r-1][c-1:c+2])
A[r][-1] += min(A[r-1][-2], A[r-1][-1])
return min(A[-1])