1. 程式人生 > >LeetCode-Minimum Falling Path Sum

LeetCode-Minimum Falling Path Sum

一、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;
    }
}