|
| 1 | +## 931. Minimum Falling Path Sum |
| 2 | + |
| 3 | +### Question: |
| 4 | +Given a square array of integers A, we want the minimum sum of a falling path through A. |
| 5 | + |
| 6 | +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. |
| 7 | + |
| 8 | +``` |
| 9 | +Example 1: |
| 10 | +
|
| 11 | +Input: [[1,2,3],[4,5,6],[7,8,9]] |
| 12 | +Output: 12 |
| 13 | +Explanation: |
| 14 | +The possible falling paths are: |
| 15 | +* [1,4,7], [1,4,8], [1,5,7], [1,5,8], [1,5,9] |
| 16 | +* [2,4,7], [2,4,8], [2,5,7], [2,5,8], [2,5,9], [2,6,8], [2,6,9] |
| 17 | +* [3,5,7], [3,5,8], [3,5,9], [3,6,8], [3,6,9] |
| 18 | +
|
| 19 | +The falling path with the smallest sum is [1,4,7], so the answer is 12. |
| 20 | +``` |
| 21 | + |
| 22 | +Note: |
| 23 | +* 1 <= A.length == A[0].length <= 100 |
| 24 | +* -100 <= A[i][j] <= 100 |
| 25 | + |
| 26 | + |
| 27 | +### Solution: |
| 28 | +* Method 1: DP O(MN) AC 96.21% |
| 29 | + ```Java |
| 30 | + class Solution { |
| 31 | + public int minFallingPathSum(int[][] A) { |
| 32 | + int len = A.length; |
| 33 | + if(len == 0) return 0; |
| 34 | + int[][] dp = new int[len][len]; |
| 35 | + for(int i = 0; i < len; i++){ |
| 36 | + dp[0][i] = A[0][i]; |
| 37 | + } |
| 38 | + for(int i = 1; i < len; i++){ |
| 39 | + for(int j = 0; j < len; j++){ |
| 40 | + dp[i][j] = Math.min(Math.min(j > 0 ? dp[i - 1][j - 1]: Integer.MAX_VALUE, j + 1 < len ? dp[i - 1][j + 1]: Integer.MAX_VALUE), dp[i - 1][j]) + A[i][j]; |
| 41 | + } |
| 42 | + } |
| 43 | + int res = Integer.MAX_VALUE; |
| 44 | + for(int i = 0; i < len; i++) |
| 45 | + res = Math.min(res, dp[len - 1][i]); |
| 46 | + return res; |
| 47 | + } |
| 48 | + } |
| 49 | + ``` |
| 50 | + |
0 commit comments