← Home

931. Minimum Falling Path Sum

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
dynamic programmingC++Markdown
931

Let's make this one less mysterious. For 931. Minimum Falling Path Sum, the solution in this repository is mainly a dynamic programming solution.

Guide

What?

Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: dynamic programming.

The notes already sitting in the source point us in the right direction:

  • Recursion
  • TLE

Guide

When?

Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are minFallingPathSumR, minFallingPathSum, arr.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(N^2), space: O(1)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Recursion
02//TLE
03
04class Solution {
05public:
06    int N;
07    
08    int minFallingPathSumR(vector<vector<int>>& A, int row, int col) {
09        
10        //invalid index, ignore it
11        if(col < 0 || col >= N) return INT_MAX;
12        //stop the recursion
13        if(row >= N) return 0;
14        //last row
15        if(row == N-1) return A[row][col];
16        
17        int x = A[row][col] + min({minFallingPathSumR(A, row+1, col-1), minFallingPathSumR(A, row+1, col), minFallingPathSumR(A, row+1, col+1)});
18        
19        // cout << row << " " << col << " " << x << endl;
20        
21        return x;
22    };
23    
24    int minFallingPathSum(vector<vector<int>>& A) {
25        N = A.size();
26        vector<int> arr(N);
27        
28        for(int col = 0; col < N; col++){
29            arr[col] = A[0][col] + min({minFallingPathSumR(A, 1, col-1), minFallingPathSumR(A, 1, col), minFallingPathSumR(A, 1, col+1)});
30        }
31        
32        return *min_element(arr.begin(), arr.end());
33    }
34};
35
36//dp
37//time: O(N^2), space: O(1)
38//Runtime: 28 ms, faster than 6.41% of C++ online submissions for Minimum Falling Path Sum.
39//Memory Usage: 9.3 MB, less than 100.00% of C++ online submissions for Minimum Falling Path Sum.
40class Solution {
41public:
42    int minFallingPathSum(vector<vector<int>>& A) {
43        int N = A.size();
44        vector<vector<int>> dp(N+2, vector<int>(N+2, INT_MAX));
45        
46        //dp: wrap A with a margin of width 1
47        for(int i = 0; i < N; i++){
48            for(int j = 0; j < N; j++){
49                dp[i+1][j+1] = A[i][j];
50            }
51        }
52        
53        //skip last row
54        for(int row = N-1; row >= 1; row--){ //[0,N-2]+1
55            for(int col = 1; col <= N; col++){ //[0,N-1]+1
56                dp[row][col] += min({dp[row+1][col-1], dp[row+1][col], dp[row+1][col+1]});
57            }
58        }
59        
60        return *min_element(dp[1].begin(), dp[1].end());
61    }
62};

Cost

Complexity

Time
O(N^2), space: O(1)
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.