题解 | #迷宫问题# dfs + 回溯

迷宫问题

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

#include<bits/stdc++.h>
using namespace std;

vector<vector<int>> res;
vector<vector<int>> path;
void dfs(int x, int y, vector<vector<int>> &map)
{
    path.push_back({x,y});
    map[x][y] = 1;
    if(x == map.size() - 1 && y == map[0].size() - 1)
    {
        res = path;
        return;
    }
    if(x + 1 < map.size() && map[x + 1][y] == 0)
    {
        dfs(x + 1, y, map);
    }
    if(y + 1 < map[0].size() && map[x][y + 1] == 0)
    {
        dfs(x, y + 1, map);
    }
    if(x - 1 >= 0 && map[x - 1][y] == 0)
    {
        dfs(x - 1, y, map);
    }
    if(y - 1 >= 0 && map[x][y - 1] == 0)
    {
        dfs(x, y - 1, map);
    }
    path.pop_back();
    map[x][y] = 0;
}

int main()
{
    int row, column;
    cin >> row >> column;
    vector<vector<int>> map(row, vector<int>(column));
    for(int i = 0; i < row; ++i)
    {
        for(int j = 0; j < column; ++j)
        {
            cin >>  map[i][j];
        }
    }
    dfs(0, 0, map);
    for(int i = 0; i < res.size(); ++i)
    {
        cout << "(" << res[i][0] << "," << res[i][1]<< ")" << endl;
    }
    return 0;
}
全部评论
该牛油正在参与牛客写题解薅羊毛的活动,牛币,周边,京东卡超多奖品放送,活动进入倒计时!快来捡漏啦https://www.nowcoder.com/discuss/888949?source_id=profile_create_nctrack&channel=-1
点赞 回复 分享
发布于 2022-04-27 12:12

相关推荐

Twilight_m...:经典我朋友XXXX起手,这是那种经典的不知道目前行情搁那儿胡编乱造瞎指导的中年人,不用理这种**
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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