Minimum Path Cost in a Grid LeetCode solution in JavaScript

1
var minPathCost = function (grid, moveCost) {
2
const dfs = (r, c, dp) => {
3
if (r === grid.length || c === grid[r].length) return 0;
4
if (dp[r][c] !== undefined) return dp[r][c];
5

6
// current cost
7
const cost = grid[r][c],
8
nextRow = r + 1;
9

10
if (nextRow === grid.length) return cost;
11

12
let nextMoveCost = Number.MAX_SAFE_INTEGER;
13
for (let nextCol = 0; nextCol < grid[nextRow].length; nextCol++) {
14
nextMoveCost = Math.min(
15
nextMoveCost,
16
dfs(nextRow, nextCol, dp) + moveCost[cost][nextCol] /*path cost*/
17
);
18
}
19
return (dp[r][c] =
20
cost + (nextMoveCost === Number.MAX_SAFE_INTEGER ? 0 : nextMoveCost));
21
};
22

23
let minCost = Number.MAX_SAFE_INTEGER;
24
const dp = Array(grid.length)
25
.fill()
26
.map(() => Array(grid[0].length).fill());
27
for (let c = 0; c < grid[0].length; c++) {
28
minCost = Math.min(minCost, dfs(0, c, dp));
29
}
30
return minCost;
31
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0