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 mini = INT_MAX;
        for (int k = max(0, j - 1); k < min(n, j + 2); ++k)
          mini = min(mini, A[i - 1][k]);
        A[i][j] += mini;
      }

    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 min = Integer.MAX_VALUE;
        for (int k = Math.max(0, j - 1); k < Math.min(n, j + 2); ++k)
          min = Math.min(min, A[i - 1][k]);
        A[i][j] += min;
      }

    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):
        mini = math.inf
        for k in range(max(0, j - 1), min(n, j + 2)):
          mini = min(mini, A[i - 1][k])
        A[i][j] += mini

    return min(A[-1])