Sponsored
Sponsored
Using a dynamic programming matrix, you can start from the second-last row of the matrix and calculate the minimum path sum by traversing through possible paths (directly below, diagonally left, and diagonally right). Update the matrix in-place to use constant space.
Time Complexity: O(n^2) because each element is visited once.
Space Complexity: O(1) since the computations are done in place.
1#include <stdio.h>
2#include <limits.h>
3
4int minFallingPathSum(int** matrix, int matrixSize, int* matrixColSize) {
5 for (int row = matrixSize - 2; row >= 0; row--) {
6 for (int col = 0; col < matrixColSize[row]; col++) {
7 int best = matrix[row + 1][col];
8 if (col > 0) {
9 best = (best < matrix[row + 1][col - 1]) ? best : matrix[row + 1][col - 1];
10 }
11 if (col < matrixColSize[row + 1] - 1) {
12 best = (best < matrix[row + 1][col + 1]) ? best : matrix[row + 1][col + 1];
13 }
14 matrix[row][col] += best;
15 }
16 }
17 int minSum = INT_MAX;
18 for (int i = 0; i < matrixColSize[0]; i++) {
19 if(matrix[0][i] < minSum) {
20 minSum = matrix[0][i];
21 }
22 }
23 return minSum;
24}
25
In the C solution, we iterate from the second-last row to the first row, and for each element, we compute the minimum sum from possible paths below. We update the original matrix with these minimum values and finally compute the minimum value in the first row.
For this approach, we use recursion with memoization to explore paths starting from the first row to the last row. We store intermediate results to avoid redundant calculations.
Time Complexity: O(n^2) due to memoization reducing redundant calculations.
Space Complexity: O(n^2) due to the memoization table.
1#include <vector>
#include <algorithm>
using namespace std;
vector<vector<int>> memo;
int dfs(vector<vector<int>>& matrix, int row, int col) {
int n = matrix.size();
if (row == n) return 0;
if (memo[row][col] != INT_MAX) return memo[row][col];
int res = matrix[row][col] + dfs(matrix, row + 1, col);
if (col > 0) res = min(res, matrix[row][col] + dfs(matrix, row + 1, col - 1));
if (col < n - 1) res = min(res, matrix[row][col] + dfs(matrix, row + 1, col + 1));
return memo[row][col] = res;
}
int minFallingPathSum(vector<vector<int>>& matrix) {
int n = matrix.size();
memo.assign(n, vector<int>(n, INT_MAX));
int minSum = INT_MAX;
for (int col = 0; col < n; ++col) {
minSum = min(minSum, dfs(matrix, 0, col));
}
return minSum;
}
The C++ implementation utilizes memoization to store already computed sums, reducing the number of dynamic calculations and speeding up the process by tracking results in a matrix.