题目:
On a 2-dimensional grid
, there are 4 types of squares:
1
represents the starting square. There is exactly one starting square.2
represents the ending square. There is exactly one ending square.0
represents empty squares we can walk over.-1
represents obstacles that we cannot walk over.
Return the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once.
Example 1:
Input: [[1,0,0,0],[0,0,0,0],[0,0,2,-1]] Output: 2 Explanation: We have the following two paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2) 2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2)
Example 2:
Input: [[1,0,0,0],[0,0,0,0],[0,0,0,2]] Output: 4 Explanation: We have the following four paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3) 2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3) 3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3) 4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3)
Example 3:
Input: [[0,1],[2,0]] Output: 0 Explanation: There is no path that walks over every empty square exactly once. Note that the starting and ending square can be anywhere in the grid.
Note:
1 <= grid.length * grid[0].length <= 20
算法解析:采用DFS,起点为遍历找到的起点,grid[i][j] = 0, 1, 2 的点都是要覆盖的点,覆盖的点的个数为todo
满足以下条件的点为符合条件的解:1)遍历点的个数为todo;2)遍历的起点为(start_row,start_end) 值为1;3)每个点只能遍历一次,遍历过的点的标记为3 ,遍历的点只能为0,或者2; 4)当todo == 0时,遍历的点为(end_row,end_col)值为2
class Solution {
public:
vector<vector<int> > grid;
int end_row = 0, end_col = 0;
int res = 0;
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
int Row,Col;
void dfspath(int r,int c,int todo)
{
todo--;
if(todo < 0)
return;
if(r == end_row && c == end_col)
{
if(todo == 0)
res++;
return;
}
grid[r][c] = 3;
for(int k = 0; k < 4; k++)
{
int nr = r + dx[k];
int nc = c + dy[k];
if(nr >=0 && nr < Row && nc >=0 && nc < Col )
{
if(grid[nr][nc] % 2 == 0) /* 0 2*/
dfspath(nr,nc,todo);
}
}
grid[r][c] = 0;
}
int uniquePathsIII(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
this->grid = grid;
Row = m, Col = n;
int todo = 0;
int start_row = 0,start_col = 0;
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
if(grid[i][j] != -1)
todo++;
if(grid[i][j] == 1){
start_row = i;
start_col = j;
}
if(grid[i][j] == 2){
end_row = i;
end_col = j;
}
}
}
res = 0;
dfspath(start_row,start_col,todo);
return res;
}
};