leetcode 980. Unique Paths III
2024-08-29 08:46:34
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
思路:深搜, 终止条件到达目标位置,以及可到达的位置全部走了一遍,算一条路径。
class Solution {
int dx[] = {, -, , };
int dy[] = {, , -, };
public:
int uniquePathsIII(vector<vector<int>>& grid) {
int m = grid.size();
if (m == )
return ;
int n = grid[].size();
int todo = ;
int start_x, start_y, end_x, end_y;
for (int i = ; i < m; i++) {
for (int j = ; j < n; j++) {
if (grid[i][j] != -) { //记录要走的总的位置数
todo++;
if (grid[i][j] == ) { //记录起始位置
start_x = i;
start_y = j;
} else if (grid[i][j] == ) { //记录终点
end_x = i;
end_y = j;
}
}
}
}
int ans = ;
dfs(grid, start_x, start_y, end_x, end_y, todo, ans, m, n);
return ans;
}
void dfs(vector<vector<int> > &grid, int sx, int sy, const int ex, const int ey, int todo, int &ans, int row, int col) {
todo--;
if (todo < )
return ;
if (sx == ex && sy == ey) {
if (todo == ) ans++;
return;
}
//上下左右四个方向
for (int k = ; k < ; k++) {
int new_x = sx + dx[k];
int new_y = sy + dy[k];
if (new_x >= && new_x < row && new_y >= && new_y < col) {
if (grid[new_x][new_y] == || grid[new_x][new_y] == ) {
grid[new_x][new_y] = -;
dfs(grid, new_x, new_y, ex, ey, todo, ans, row, col);
grid[new_x][new_y] = ;
}
}
}
}
};
最新文章
- 玩转spring boot——结合AngularJs和JDBC
- 最短路(代码来源于kuangbin和百度)
- Android欢迎界面
- linux下的nodejs安装
- OpenCascade BRep Format Description
- Android系统默认设置
- c++中,保证头文件只被编译一次,避免多重包含的方法
- 清除HTML标记
- java_JDBC(3)
- ASP.NET MVC AJAX的调用示例
- Spark MLib:梯度下降算法实现
- datatable拆分多个
- 是否能设计一种DNN的特定网络结构来改善DNN,使得其学习起来更加高效
- 【转】Android-Input 触控笔
- mysql连续聚合
- MySQL 字段内容区分大小写
- c/c++关于指针的一点理解
- 联想G510安装win7系统
- (原)tensorflow中函数执行完毕,显存不自动释放
- WPF 每次只打开一个窗口