题解 | #迷宫问题#

迷宫问题

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

#include <climits>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int result = INT_MAX;
vector<string> res_path;
void bp(vector<vector<int>> maze, int n, int m ,int i, int j, int count, vector<string> &path, vector<vector<bool>> &used){
    if (i >= n || j >= m || i < 0 || j < 0)
        return;
    if (i == n - 1 && j == m - 1){
        if (result > count){
            result = count;
            res_path = path;
        }   
        return;
    }
    //you
    if (j < m - 1 && maze[i][j + 1] == 0 && !used[i][ j + 1]){
        string tmp = '(' + to_string(i) + ',' + to_string(j + 1) +')';
        used[i][j + 1] = true;
        path.push_back(tmp);
        bp(maze, n, m, i, j + 1, count + 1, path, used);
        path.pop_back();
        used[i][j + 1] = false;
    }
    //shang
    if ( i < n - 1 && maze[i + 1][j] == 0 && !used[i + 1][j]){
        string tmp = '(' + to_string(i + 1) + ',' + to_string(j) +')';
        used[i + 1][j] = true;
        path.push_back(tmp);
        bp(maze, n, m, i + 1, j, count + 1, path, used);
        path.pop_back();
        used[i + 1][j] = false;
    }
    
    //zuo
    if (0 < j && maze[i][j - 1] == 0 && !used[i][j - 1]){
        string tmp = '(' + to_string(i) + ',' + to_string(j - 1) +')';
        path.push_back(tmp);
        used[i][j - 1] = true;
        bp(maze, n, m, i, j - 1, count + 1, path, used);
        path.pop_back();
        used[i][j - 1] = false;
    }
    //xia
    if (0 < i && maze[i - 1][j] == 0 && !used[i - 1][j]){
        string tmp = '(' + to_string(i - 1) + ',' + to_string(j) +')';
        path.push_back(tmp);
        used[i - 1][j] = true;
        bp(maze, n, m, i - 1, j, count + 1, path, used);
        path.pop_back();
        used[i - 1][j] = false;
    }
}

int main() {
    int n,m;
    cin>>n>>m;
    vector<vector<int>> maze(n, vector<int>(m, 0));
    int x;
    for (int i = 0; i < n; i++){
        for (int j = 0; j < m; j++){
            cin>>x;
            maze[i][j] = x;
        }
    }
    vector<vector<bool>> used(n, vector<bool>(m, false));
    vector<string> path;
    path.push_back("(0,0)");
    bp(maze, n, m, 0, 0, 0, path, used);
    for (auto it : res_path)
        cout<< it<<endl;
    //cout << result;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

买蜜雪也用卷:我觉得应该没有哪个人敢说自己熟练使用git,代码分支一复杂还是得慢慢寻思一下的,不过基本的拉代码提交代码还有分支什么的是应该会
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-20 18:18
是不是意味着秋招就完蛋了
花不开柳成荫:如果你是Java,是的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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