HJ43 迷宫问题文章来源地址https://www.toymoban.com/news/detail-660272.html
#include <bits/stdc++.h>
using namespace std;
void dfs(vector<vector<int>>& map, vector<pair<int,int>>& paths, int x, int y){
//记录走过,更新路径
// cout << x << y << endl;
map[x][y] = 1;
pair<int, int> point(x, y);
paths.push_back(point);
int n = map.size()-1;
int m = map[0].size()-1;
if(x == n && y == m){
//输出paths
for(auto &x : paths){
cout << "(" << x.first << "," << x.second << ")" <<endl;
}
return;
}
//上下左右搜索, 注意越界的判断要在前面
if(x - 1 >=0 && map[x - 1][y] == 0){
dfs(map, paths, x-1, y);
}
if(x + 1 <= n && map[x + 1][y] == 0){
dfs(map, paths, x+1, y);
}
if(y - 1 >=0 && map[x][y-1] == 0){
dfs(map, paths, x, y-1);
}
if(y + 1 <= m && map[x][y+1] == 0){
dfs(map, paths, x, y + 1);
}
paths.pop_back();
map[x][y] = 0;
}
int main() {
int n, m;
cin >> n >> m;
// cout << a << b << endl;
vector<vector<int>> map(n, vector<int>(m));
// vector<vector<int>> walked(a, vector<int>(b, 0));
for(int i = 0; i < map.size(); i++){
for(int j = 0; j < map[i].size(); j++){
cin >> map[i][j];
}
}
//bfs
vector<pair<int, int>> paths;
// vector<pair<int, int>> res;
dfs(map, paths, 0, 0);
}
// 64 位输出请用 printf("%lld")
文章来源:https://www.toymoban.com/news/detail-660272.html
到了这里,关于迷宫DFS问题(二维vector, pair,模板题)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!