Maximum Number of Moves in a Grid - DP [JS]
Solution: DP - Recursion w/ Memoization
Memoize each dp(row, col)
, where dp(row, col)
= the maximum number of moves we can perform starting from (row, col)
.
For each dp(row, col)
, traverse in three directions and record the maximum number of moves.
m = number of rows
, n = number of columns
Time Complexity: O(mn)
Space Complexity: O(mn)
var maxMoves = function(grid) {
let m = grid.length, n = grid[0].length;
let memo = Array(m).fill(0).map(() => Array(n).fill(-1));
const directions = [[-1, 1], [0, 1], [1, 1]];
let maxMoves = 0;
for (let i = 0; i < m; i++) {
maxMoves = Math.max(maxMoves, dp(i, 0));
}
return maxMoves;
function dp(row, col) {
if (col === n - 1) return 0;
if (memo[row][col] !== -1) return memo[row][col];
let ans = 0;
for (let [x, y] of directions) {
let newRow = row + x, newCol = col + y;
if (newRow < 0 || newRow >= m || newCol < 0 || newCol >= n || grid[newRow][newCol] <= grid[row][col]) continue; // out of bounds or value is not bigger
ans = Math.max(ans, 1 + dp(newRow, newCol));
}
return memo[row][col] = ans;
}
};
Comments
Post a Comment