LeetCode Solutions

931. Minimum Falling Path Sum

Time: $O(n^2)$

Space: $O(1)$

			

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 *min_element(begin(A[n - 1]), end(A[n - 1]));
  }
};
			

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

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])