2684. 矩阵中移动的最大次数
题目链接:2684. 矩阵中移动的最大次数
代码如下:
//深度优先遍历
//参考:https://leetcode.cn/problems/maximum-number-of-moves-in-a-grid/solutions/2269244/cong-ji-yi-hua-sou-suo-dao-di-tui-by-end-pgq3
class Solution {
public:
void dfs(vector<vector<int>>& grid,int i,int j)
{
int m=grid.size(),n=grid[0].size();
res=max(res,j);
if(res==n-1)//res以达到最大值
return;
//向右上/右/右下走一步
for(int k=max(i-1,0);k<min(i+2,m);k++)
{
if(grid[k][j+1]>grid[i][j])
dfs(grid,k,j+1);
}
grid[i][j]=0;
}
int maxMoves(vector<vector<int>>& grid)
{
res=0;
for(int i=0;i<grid.size();i++)
dfs(grid,i,0);
return res;
}
private:
int res;
};