[LeetCode] Maximum Number of Moves in a Grid

2684. Maximum Number of Moves in a Grid

You are given a 0-indexed m x n matrix grid consisting of positive integers.

You can start at any cell in the first column of the matrix, and traverse the grid in the following way:

  • From a cell (row, col), you can move to any of the cells: (row - 1, col + 1), (row, col + 1) and (row + 1, col + 1) such that the value of the cell you move to, should be strictly bigger than the value of the current cell.

Return the maximum number of moves that you can perform.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
int helper(vector<vector<int>>& dp, vector<vector<int>>& A, int y, int x, int n, int m) {
if(dp[y][x] != -1) return dp[y][x];
int& res = dp[y][x] = 0;
if(x + 1 < m) {
if(y and A[y][x] < A[y-1][x+1]) res = max(res, helper(dp,A,y-1,x+1,n,m) + 1);
if(A[y][x] < A[y][x+1]) res = max(res, helper(dp,A,y,x+1,n,m) + 1);
if(y + 1 < n and A[y][x] < A[y+1][x+1]) res = max(res, helper(dp,A,y+1,x+1,n,m) + 1);
}
return res;
}
public:
int maxMoves(vector<vector<int>>& grid) {
int n = grid.size(), m = grid[0].size();
vector<vector<int>> dp(n,vector<int>(m,-1));
int res = 0;
for(int i = 0; i < n; i++) {
dp[i][0] = helper(dp,grid,i,0,n,m);
res = max(res, dp[i][0]);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/05/14/PS/LeetCode/maximum-number-of-moves-in-a-grid/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.