Skip to content

931. Minimum Falling Path Sum 👍

  • Time: $O(n^2)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  int minFallingPathSum(vector<vector<int>>& A) {
    const int n = A.size();

    for (int i = 1; i < n; ++i)
      for (int j = 0; j < n; ++j) {
        int mn = INT_MAX;
        for (int k = max(0, j - 1); k < min(n, j + 2); ++k)
          mn = min(mn, A[i - 1][k]);
        A[i][j] += mn;
      }

    return ranges::min(A[n - 1]);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public int minFallingPathSum(int[][] A) {
    final int n = A.length;

    for (int i = 1; i < n; ++i)
      for (int j = 0; j < n; ++j) {
        int mn = Integer.MAX_VALUE;
        for (int k = Math.max(0, j - 1); k < Math.min(n, j + 2); ++k)
          mn = Math.min(mn, A[i - 1][k]);
        A[i][j] += mn;
      }

    return Arrays.stream(A[n - 1]).min().getAsInt();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def minFallingPathSum(self, A: list[list[int]]) -> int:
    n = len(A)

    for i in range(1, n):
      for j in range(n):
        mn = math.inf
        for k in range(max(0, j - 1), min(n, j + 2)):
          mn = min(mn, A[i - 1][k])
        A[i][j] += mn

    return min(A[-1])