Minimum Path Cost in a Grid - Dynamic Programming [JS]
- Get link
- X
- Other Apps
By
Anna An
on
Solution: Dynamic Programming
We only need information about the previous and current row.
Use two arrays of size n (prev and curr) to keep track of the minimum cost to travel to each cell in a row.
For each cell in a row, take the minimum cost of going from each cell in the previous row.
m = number of rows,n = number of columns
Time Complexity: O(m * n * n)174ms
Space Complexity: O(n) 55.5MB
var minPathCost = function(grid, moveCost) {
let m = grid.length, n = grid[0].length;
let prev = [...grid[0]];
for (let i = 1; i < m; i++) {
let curr = Array(n).fill(Infinity);
for (let j = 0; j < n; j++) { // curr row's columns
for (let k = 0; k < n; k++) { // prev row's columns
let prevCell = grid[i - 1][k], currCell = grid[i][j];
curr[j] = Math.min(prev[k] + moveCost[prevCell][j] + currCell, curr[j]);
}
}
prev = curr;
}
return Math.min(...prev);
};
javascript
- Get link
- X
- Other Apps
Comments
Post a Comment