[LeetCode] Minimum Falling Path Sum

931. Minimum Falling Path Sum

Given an n x n array of integers matrix, return the minimum sum of any falling path through matrix.

A falling path starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position (row, col) will be (row + 1, col - 1), (row + 1, col), or (row + 1, col + 1).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int minFallingPathSum(vector<vector<int>>& matrix) {
int n = matrix.size(), m = matrix[0].size();
for(int i = 1; i < n; i++) {
matrix[i][0] = matrix[i][0] + min(matrix[i-1][0], matrix[i-1][1]);
for(int j = 1; j < m - 1; j ++) {
matrix[i][j] = matrix[i][j] + min({matrix[i-1][j], matrix[i-1][j-1], matrix[i-1][j+1]});
}
matrix[i][m-1] = matrix[i][m-1] + min(matrix[i-1][m-1], matrix[i-1][m-2]);
}
return *min_element(matrix[n-1].begin(), matrix[n-1].end());
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/13/PS/LeetCode/minimum-falling-path-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.