#931. Minimum Falling Path Sum
var minFallingPathSum = function(matrix) {
if (!matrix || matrix.length === 0) {
return 0;
}
const rows = matrix.length;
const cols = matrix[0].length;
// Memoization cache
const memo = {};
function findMinPath(row, col) {
// Base case: if we reach the first row, return the value at that position
if (row === 0) {
return matrix[row][col];
}
// Check if the result is already memoized
if (memo.hasOwnProperty(`${row}-${col}`)) {
return memo[`${row}-${col}`];
}
// Calculate the minimum falling path sum recursively
let left = findMinPath(row - 1, Math.max(col - 1, 0));
let up = findMinPath(row - 1, col);
let right = findMinPath(row - 1, Math.min(col + 1, cols - 1));
// Memoize the result
memo[`${row}-${col}`] = matrix[row][col] + Math.min(left, up, right);
// Return the memoized result
return memo[`${row}-${col}`];
}
// Initialize the result with Infinity
let result = Infinity;
// Call the recursive function for each element in the first row
for (let i = 0; i < cols; i++) {
result = Math.min(result, findMinPath(rows - 1, i));
}
return result;
};
Solved with chatGPT.
ย