LeetCode-Minimum Falling Path Sum

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Apple_hzc/article/details/83474489

一、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.


二、Analyzation

可以从数组第二行开始,从第0列起,每个位置加上左上、正上和右上方三个数字中最小的那一个,如果出了边界,则将那个位置的数字置为MAX,如此向下累加,最后一行中最小的数字即为所求。


三、Accepted code

class Solution {
    public int minFallingPathSum(int[][] A) {
        if (A == null || A.length == 0) {
            return 0;
        }
        int m = A.length;
        int n = A[0].length;
        for (int i = 1; i < m; i++) {
            for (int j = 0; j < n; j++) {
                int a, b, c;
                if (j == 0) {
                    a = Integer.MAX_VALUE;
                } else {
                    a = A[i - 1][j - 1];
                }
                if (j == n - 1) {
                    c = Integer.MAX_VALUE;
                } else {
                    c = A[i - 1][j + 1];
                }
                b = A[i - 1][j];
                A[i][j] += Math.min(Math.min(a, b), c);
            }
        }
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < n; i++) {
            if (min > A[m - 1][i]) {
                min = A[m - 1][i];
            }
        }
        return min;
    }
}

猜你喜欢

转载自blog.csdn.net/Apple_hzc/article/details/83474489