931. Minimum Falling Path Sum

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

931. Minimum Falling Path Sum

1. 题目
题目链接

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.

2. 题目分析
在一个n阶矩阵中,从第一行的任一元素开始,找到到达最后一行时的最短路径,但要求,选择路径中的下一个元素,必须与当前元素的距离不超过1,即如果当前元素处于(i.j),则下一个元素只能是(i+1,j-1),(i+1,j),(i+1,j+1)中的一个。

3. 解题思路
这题其实与找在m*n矩阵中从一个元素开始到达最右下角元素的最短路径的题型差不多,只是行走规则和到达的目的地不一样而已。所以都是动态规划的题目。按照我之前分析的动态规划的思路:

  • 首先确定状态,用dp[i][j]表示到达第i行第j列时的最小路径(从第0行开始);
  • 初始化,对第0行的所以状态进行初始化,即dp[0][j] = A[0][j];
  • 找状态转移方程,因为到达(i,j),只可能是(i-1,j-1),(i-1,j),(i-1,j+1)这三个点,所以只要比较这三者,找到最小值就行,需要注意的是,如果当前i=0,则,没哟j-1;如果当前i=length-1;则没有j+1。

4. 代码实现(java)

package com.algorithm.leetcode.dynamicAllocation;

/**
 * Created by 凌 on 2019/1/27.
 * 注释:931. Minimum Falling Path Sum
 */
public class MinFallingPathSum {
    public int minFallingPathSum(int[][] A) {
        int len = A.length;
        if (A == null || len == 0){
            return 0;
        }
        int[][] dp =new int[len][len];
        for (int j = 0; j < len; j++) {
            dp[0][j] = A[0][j];
        }
        for (int i = 1; i < len; i++) {
            for (int j = 0; j < len; j++) {
                dp[i][j] = dp[i-1][j];
                if (j>=1){
                    dp[i][j] = Math.min(dp[i][j],dp[i-1][j-1]);
                }
                if (j+1<len){
                    dp[i][j] = Math.min(dp[i][j],dp[i-1][j+1]);
                }
                dp[i][j] += A[i][j];
            }
        }
        int min = Integer.MAX_VALUE;
        for (int j = 0; j < len; j++) {
            min = Math.min(dp[len-1][j],min);
        }
        return min;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_35923749/article/details/86676729