迷宫DFS问题(二维vector, pair,模板题)

HJ43 迷宫问题

#include 
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> walked(a, vector(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> res;
    dfs(map, paths, 0, 0);
}
// 64 位输出请用 printf("%lld")

你可能感兴趣的:(深度优先,算法)