Maximum Number of Moves in a Grid - DFS + BFS + DP solutions
Problem Statement:
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.
Example 1:
Input: grid = [[2,4,3,5],[5,4,9,3],[3,4,2,11],[10,9,13,15]] Output: 3 Explanation: We can start at the cell (0, 0) and make the following moves: - (0, 0) -> (0, 1). - (0, 1) -> (1, 2). - (1, 2) -> (2, 3). It can be shown that it is the maximum number of moves that can be made.
Example 2:
Input: grid = [[3,2,4],[2,1,9],[1,1,7]] Output: 0 Explanation: Starting from any cell in the first column we cannot perform any moves.
Constraints:
m == grid.length
n == grid[i].length
2 <= m, n <= 1000
4 <= m * n <= 105
1 <= grid[i][j] <= 106
Solution:
DFS:
class Solution {
public:
int dfs(int i, int j, vector<vector<int>>&grid, vector<vector<bool>>&visited, int m, int n)
{
if (j==n-1) return 0;
int res=0;
visited[i][j] = true;
for (int ii=max(i-1,0); ii<=min(m-1,i+1); ii++)
if (grid[ii][j+1]>grid[i][j] && !visited[ii][j+1])
res = max(res, 1+dfs(ii,j+1,grid,visited,m,n));
return res;
}
int maxMoves(vector<vector<int>>& grid)
{
int m=grid.size(), n=grid[0].size(), res=0;
vector<vector<bool>> visited(m, vector<bool>(n,false));
for (int i=0; i<m; i++)
{
res = max(res, dfs(i, 0, grid, visited, m, n));
if (res==n-1) return res;
}
return res;
}
};
BFS:
class Solution {
public:
int maxMoves(vector<vector<int>>& grid)
{
int m=grid.size(), n=grid[0].size(), res=0;
queue<pair<int,int>> Q;
vector<vector<bool>> visited(m, vector<bool>(n,false));
for(int i=0; i<m; i++)
{
Q.push({i,0});
visited[i][0] = true;
}
while(!Q.empty())
{
for (int i=Q.size(); i>0; i--)
{
int curY=Q.front().first, curX=Q.front().second;
if (curX==n-1) return n-1;
Q.pop();
for (int nbdY=max(0,curY-1); nbdY<=min(m-1,curY+1); nbdY++)
{
int nbdX = curX+1;
if (grid[nbdY][nbdX]>grid[curY][curX] && !visited[nbdY][nbdX])
{
visited[nbdY][nbdX] = true;
Q.push({nbdY,nbdX});
}
}
}
res++;
}
return res-1;
}
};
DFS with DP
class Solution {
public:
int dfs(int i, int j, vector<vector<int>>&grid, int m, int n, vector<vector<int>>&A)
{
if (A[i][j]!=-1) return A[i][j];
if (j==n-1) return 0;
int a = (i>0 && grid[i-1][j+1]>grid[i][j]) ? 1+dfs(i-1,j+1,grid,m,n,A) : 0;
int b = (grid[i][j+1]>grid[i][j]) ? 1+dfs(i,j+1,grid,m,n,A) : 0;
int c = (i<m-1 && grid[i+1][j+1]>grid[i][j]) ? 1+dfs(i+1,j+1,grid,m,n,A) : 0;
return A[i][j] = max({a,b,c});
}
int maxMoves(vector<vector<int>>& grid)
{
int m=grid.size(), n=grid[0].size(), res=0;
vector<vector<int>> A(m, vector<int>(n,-1));
for (int i=0; i<m; i++)
{
res = max(res, dfs(i,0,grid,m,n,A));
if (res==n-1) return res;
}
return res;
}
};