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
classSolution { public: intminFallingPathSum(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()); } };