题解 | 迷宫问题

迷宫问题

https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc

#include <iostream>
#include <vector>
using namespace std;

vector<vector<int>> path;
vector<vector<int>> dir = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
bool found = false;

void dfs(vector<vector<int>>& maze, int x, int y) {
    int h = maze.size();
    int w = maze[0].size();

    maze[x][y] = 1;
    path.push_back({x, y});
    if(x == h-1 && y == w-1) {
        found = true;
        return ;
    }   

    for(int i = 0; i < 4; ++i) {
        int xx = x + dir[i][0];
        int yy = y + dir[i][1];
        if(xx >= 0 && yy >= 0 && xx < h && yy < w && !maze[xx][yy]){
            dfs(maze, xx, yy);
            if(found) return ;
        }
    }
    path.pop_back();
}

int main() {
    int h, w;
    cin >> h >> w;
    vector<vector<int>> maze(h, vector<int>(w, 0));
    for(int i = 0; i < h; ++i) {
        for(int j = 0; j < w; ++j) {
            cin >> maze[i][j];
        }
    }
    path.clear();

    dfs(maze, 0, 0);
    for(auto p: path) {
        cout << "(" << p[0] << "," << p[1] << ")" << endl;
    }
    return 0;
}

全部评论

相关推荐

渴望wlb的牛油果很...:直说卡第一学历不就行了 非得拐弯抹角
点赞 评论 收藏
分享
10-15 20:01
已编辑
上海大学 Java
钉钉什么垃圾公司,约面鸽人
Syca_:途虎养车给我定了我这边早上六点的笔试,睡了四个小时起来难受的要命,告诉我面试时间是两天后的凌晨四点
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务