1 题目
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)
2 尝试解
2.1 分析
在二维矩阵中,1代表起点,2代表终点,-1代表障碍物,0代表可通行。问从起点到终点,经过所有可通行位置一次且仅一次,求这样的路径数。
典型的深度优先搜索算法。首先统计所有可通行位置的总数total。然后从起点开始,向上下左右各采用深度优先搜索dfsPath(i,j,length,total),表示从当前位置[i,j]开始,步数为length,
如果当前位置越界,返回0
如果当前位置为-1或者1,返回0
如果当前位置为2,统计走过的步数length,如果length == total,此路径满足要求,返回1。
如果当前位置为0,将当前位置设为1,result = dfsPath(i-1,j,length+1,total)+dfsPath(i+1,j,length+1,total)+dfsPath(i,j-1,length+1,total)+dfsPath(i,j+1,length+1,total),然后重置当前位置为0,返回result
2.2 代码
class Solution {
public:
int dfsPath(vector<vector<int>>&grid,int i, int j, int length, int total){
if(i <0 || i >= grid.size() || j <0 || j>= grid[0].size() || grid[i][j] == -1) return 0;
if(grid[i][j] == 2) {
return (length == total?1:0);
}
if(grid[i][j] == -1 || grid[i][j] == 1) return 0;
grid[i][j] = 1;
int result = 0;
result = dfsPath(grid,i-1,j,length+1,total)+dfsPath(grid,i+1,j,length+1,total)+dfsPath(grid,i,j-1,length+1,total)+dfsPath(grid,i,j+1,length+1,total);
grid[i][j] = 0;
return result;
}
int uniquePathsIII(vector<vector<int>>& grid) {
int total = 0;
int result = 0;
for(int i = 0; i < grid.size(); i++){
for(int j = 0; j < grid[0].size(); j++){
if(grid[i][j] == 0)
total += 1;
}
}
for(int i = 0; i < grid.size(); i++){
for(int j = 0; j < grid[0].size(); j++){
if(grid[i][j] == 1)
result += dfsPath(grid,i-1,j,0,total)+dfsPath(grid,i+1,j,0,total)+dfsPath(grid,i,j-1,0,total)+dfsPath(grid,i,j+1,0,total);
}
}
return result;
}
};