题解:
class Solution
{
int n,m;
bool st[100][100];
int flag;
int dx[8]={-1,-2,-2,-1,1,2,2,1};
int dy[8]={-2,-1,1,2,2,1,-1,-2};
public:
bool checkValidGrid(vector<vector<int>>& grid)
{
m = grid.size();
n = grid[0].size();
dfs(grid,0,0,0);
return flag;
}
void dfs(vector<vector<int>>& grid,int i,int j,int u)
{
st[i][j] = true;
if(grid[i][j] != u) return;
if(grid[i][j] == n * m -1)//遍历完所有数组了就可以返回了
{
flag = true;
return;
}
for(int k=0;k<8;k++)
{
int x=i+dx[k];
int y=j+dy[k];
if(x>=0 && x<n && y>=0 && y<m && !st[x][y])
{
st[x][y]=true;
dfs(grid,x,y,u+1);
st[x][y]=false;
}
}
}
};