LeetCode 931: Minimum Falling Path Sum Solution

Master LeetCode problem 931 (Minimum Falling Path Sum), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

931. Minimum Falling Path Sum

Problem Explanation

Explanation

To solve this problem, we can use dynamic programming. We will iterate through the matrix starting from the second row, and for each cell, we will update the value to be the minimum of the adjacent cells in the row above plus the current cell's value. Finally, we return the minimum value in the last row, which represents the minimum falling path sum.

  • Time complexity: O(n^2) where n is the size of the matrix
  • Space complexity: O(1)

Solution Code

class Solution {
    public int minFallingPathSum(int[][] matrix) {
        int n = matrix.length;
        
        for (int i = 1; i < n; i++) {
            for (int j = 0; j < n; j++) {
                int minPrev = matrix[i - 1][j];
                if (j > 0) {
                    minPrev = Math.min(minPrev, matrix[i - 1][j - 1]);
                }
                if (j < n - 1) {
                    minPrev = Math.min(minPrev, matrix[i - 1][j + 1]);
                }
                matrix[i][j] += minPrev;
            }
        }
        
        int minSum = Integer.MAX_VALUE;
        for (int num : matrix[n - 1]) {
            minSum = Math.min(minSum, num);
        }
        
        return minSum;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 931 (Minimum Falling Path Sum)?

This page provides optimized solutions for LeetCode problem 931 (Minimum Falling Path Sum) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 931 (Minimum Falling Path Sum)?

The time complexity for LeetCode 931 (Minimum Falling Path Sum) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 931 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 931 in Java, C++, or Python.

Back to LeetCode Solutions