DFS
class Solution {
int r,c;
int startX,startY;
int endX, endY;
int res = 0;
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, -1, 0, 1};
vector<vector<int>> grid;
vector<vector<bool>>visited;
void dfs(int x, int y,int k)
{
if(k < 0) return ;
if(x == endX && y == endY)
{
if(k == 0)
{
res++;
}
return ;
}
for(int i = 0; i < 4; i++)
{
int a = x + dx[i], b = y + dy[i];
if(a < 0 || a >= r || b < 0 || b >= c) continue;
if( !visited[a][b] && grid[a][b] == 0 || grid[a][b] == 2)
{
visited[a][b] = true;
dfs(a, b, k - 1);
visited[a][b] = false;
}
}
}
public:
int uniquePathsIII(vector<vector<int>>& grid) {
this->r = grid.size();
this->c = grid[0].size();
this->grid = grid;
this->visited = vector<vector<bool>>(r, vector<bool>(c, false));
int cnt0 = 0;
for(int i = 0; i < r; i++)
{
for(int j = 0; j < c; j++)
{
if(grid[i][j] != -1)
{//0,1,2个数
cnt0++;
}
if(grid[i][j] == 1)
{
startX = i;
startY = j;
}
else if(grid[i][j] == 2)
{
endX = i;
endY = j;
}
}
}
dfs(startX,startY,cnt0 - 1);
return res;
}
};