class Solution {
minPathSum(grid: number[][]): number {
const m = grid.length;
const n = grid[0].length;
// Update first row sums
for (let j = 1; j < n; j++) {
grid[0][j] += grid[0][j - 1];
}
// Update first column sums
for (let i = 1; i < m; i++) {
grid[i][0] += grid[i - 1][0];
}
// Update rest of grid with min path sums
for (let i = 1; i < m; i++) {
for (let j = 1; j < n; j++) {
grid[i][j] += Math.min(grid[i - 1][j], grid[i][j - 1]);
}
}
return grid[m - 1][n - 1];
}
}
// Driver code
const grid = [
[1, 3, 1],
[1, 5, 1],
[4, 2, 1]
];
const sol = new Solution();
console.log(sol.minPathSum(grid));for (let j = 1; j < n; j++) {
grid[0][j] += grid[0][j - 1];
}
Accumulate sums along the first row since only right moves possible
for (let i = 1; i < m; i++) {
grid[i][0] += grid[i - 1][0];
}
Accumulate sums along the first column since only down moves possible
for (let i = 1; i < m; i++) {
for (let j = 1; j < n; j++) {
grid[i][j] += Math.min(grid[i - 1][j], grid[i][j - 1]);
}
}
For each cell, add the minimum of top or left cell sums to current cell value
return grid[m - 1][n - 1];
Return the minimum path sum at bottom-right cell