|
| 1 | +/** |
| 2 | + * 2684. Maximum Number of Moves in a Grid |
| 3 | + * https://leetcode.com/problems/maximum-number-of-moves-in-a-grid/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given a 0-indexed m x n matrix grid consisting of positive integers. |
| 7 | + * |
| 8 | + * You can start at any cell in the first column of the matrix, and traverse the grid in the |
| 9 | + * following way: |
| 10 | + * - From a cell (row, col), you can move to any of the cells: (row - 1, col + 1), (row, col + 1) |
| 11 | + * and (row + 1, col + 1) such that the value of the cell you move to, should be strictly bigger |
| 12 | + * than the value of the current cell. |
| 13 | + * |
| 14 | + * Return the maximum number of moves that you can perform. |
| 15 | + */ |
| 16 | + |
| 17 | +/** |
| 18 | + * @param {number[][]} grid |
| 19 | + * @return {number} |
| 20 | + */ |
| 21 | +var maxMoves = function(grid) { |
| 22 | + const rows = grid.length; |
| 23 | + const cols = grid[0].length; |
| 24 | + const memo = Array.from({ length: rows }, () => new Array(cols).fill(-1)); |
| 25 | + |
| 26 | + let result = 0; |
| 27 | + for (let row = 0; row < rows; row++) { |
| 28 | + result = Math.max(result, explore(row, 0)); |
| 29 | + } |
| 30 | + |
| 31 | + return result; |
| 32 | + |
| 33 | + function explore(row, col) { |
| 34 | + if (col === cols - 1) return 0; |
| 35 | + if (memo[row][col] !== -1) return memo[row][col]; |
| 36 | + |
| 37 | + let maxSteps = 0; |
| 38 | + const current = grid[row][col]; |
| 39 | + |
| 40 | + if (row > 0 && col + 1 < cols && grid[row - 1][col + 1] > current) { |
| 41 | + maxSteps = Math.max(maxSteps, 1 + explore(row - 1, col + 1)); |
| 42 | + } |
| 43 | + if (col + 1 < cols && grid[row][col + 1] > current) { |
| 44 | + maxSteps = Math.max(maxSteps, 1 + explore(row, col + 1)); |
| 45 | + } |
| 46 | + if (row + 1 < rows && col + 1 < cols && grid[row + 1][col + 1] > current) { |
| 47 | + maxSteps = Math.max(maxSteps, 1 + explore(row + 1, col + 1)); |
| 48 | + } |
| 49 | + |
| 50 | + memo[row][col] = maxSteps; |
| 51 | + return maxSteps; |
| 52 | + } |
| 53 | +}; |
0 commit comments