Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

931. Minimum Falling Path Sum

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)
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;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.