Link
https://leetcode.com/problems/minimum-falling-path-sum
My Code:
class Solution:
def minFallingPathSum(self, A: List[List[int]]) -> int:
Row = len(A)
Col = len(A[0])
ResultMat = [A[0]]
if Col ==1:
Sum =0
for i in range(Row):
Sum+= A[i][0]
return Sum
else:
for i in range(1,Row):
RowIList = []
for j in range(Col):
if j ==0:
Value = min(ResultMat[i-1][j],ResultMat[i-1][j+1])+A[i][j]
RowIList.append(Value)
elif j == (Col-1):
Value = min(ResultMat[i-1][j-1],ResultMat[i-1][j])+A[i][j]
RowIList.append(Value)
else:
Value = min(ResultMat[i-1][j-1],ResultMat[i-1][j],ResultMat[i-1][j+1])+ A[i][j]
RowIList.append(Value)
ResultMat.append(RowIList)
return min(ResultMat[Row-1])
Explanation:
The recursion we are using is a matrix. Mat[i][j] means the minimum value path we take going to the ith row and jth col of the original matrix. The recursion is desinged as above: For each element, there are three choices ( except for two boundary elements). we then choose the minimum of them as the choice and then we add the value at the point, to get the minimum value up to this element. Based on this method, the value at each element is the minimum value path up to this element. Hence we just need to take out all the minimum value in the last row and then take the minimum value among them as the output.