931. Minimal sum of descent path
Topic link
Source: LeetCode
Link: https://leetcode-cn.com/problems/minimum-falling-path-sum/
Title description
Given a square integer array A, we want to get the minimum sum of the descending paths through A.
The descending path can start from any element in the first row and select an element from each row. The element selected in the next row and the element selected in the current row are separated by at most one column.
Example:
Input: [[1,2,3],[4,5,6],[7,8,9]]
Output: 12
Explanation: The
possible descending 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]
and the smallest descending path is [1,4,7], so the answer is 12.
prompt:
1 <= A.length == A[0].length <= 100
-100 <= A[i][j] <= 100
Topic analysis
The main consideration is the boundary value of the array, that is, the first column and the last column, that is, when j is 0 and j is n-1.
class Solution {
public int minFallingPathSum(int[][] A) {
int n = A.length;
for(int i = n-2;i>=0;i--){
for(int j = 0;j<n;j++){
if(j==0){
A[i][j] = (A[i+1][j] > A[i+1][j+1] ? A[i+1][j+1] : A[i+1][j]) + A[i][j];
}else if(j==n-1){
A[i][j] = (A[i+1][j] > A[i+1][j-1] ? A[i+1][j-1] : A[i+1][j]) + A[i][j];
}else{
A[i][j] = min(A[i+1][j-1],A[i+1][j],A[i+1][j+1]) + + A[i][j];
}
}
}
Arrays.sort(A[0]);
return A[0][0];
}
public int min(int a,int b,int c){
b = a>b?b:a;
return b>c?c:b;
}
}