蓝桥杯练习 迷宫问题 题解

题目:
输入:
21 32
…11111111111111111111111111111
11.111111……..1111111111.1111
11.111111..111.11111111…..1111
11.11111111111.1111111111.111111
11.111111……………..111111
11.111111.11111111111.11111.1111
11.111111.11111111111.11111..111
11……….111111111.11111.1111
11111.111111111111111.11….1111
11111.111111111111111.11.11.1111
11111.111111111111111.11.11.1111
111…111111111111111.11.11.1111
111.11111111111111111….11.1111
111.11111111111111111111111.1111
111.1111.111111111111111……11
111.1111…….111111111.1111.11
111.1111.11111.111111111.1111.11
111……11111.111111111.1111111
11111111111111.111111111.111…1
11111111111111……………1.1
111111111111111111111111111111..

如上图的迷宫,入口,出口分别:左上角,右下角
“1”是墙壁,”.”是通路
求最短需要走多少步?

思路:BFS求最短路;模板
答案:53

Code:

#include <iostream>
#include <fstream>
#include <queue> 
#include <cstdio>
using namespace std;

const int maxn = 1010;
char G[maxn][maxn];
bool vis[maxn][maxn];
int dir[4][2] = {{-1, 0},{0, 1},{1, 0},{0, -1}};
int n,m;

struct Point{
    int x, y;
    int level;
}start,end,pt; 

bool alright(int x, int y){
    if(x < 0 || y < 0 || x >= n || y >= m) return false;
    if(G[x][y] == '1') return false;
    if(vis[x][y]) return false;
    return true;
}

void BFS(){
    queue<Point> q;
    q.push(start);
    vis[start.x][start.y] = true;

    while(!q.empty()){
        Point top = q.front();
        q.pop();

        for(int i = 0; i < 4; ++i){
            int xx = top.x + dir[i][0];
            int yy = top.y + dir[i][1];
            if(alright(xx, yy)){
                vis[xx][yy] = true;
                pt.x = xx;
                pt.y = yy;
                pt.level = top.level + 1;
                if(end.x == xx && end.y == yy){
                    cout<<pt.level<<endl;
                    return ;
                }
                q.push(pt);
            }
        }   
    }
}

int main(){
// fstream cin("a.txt");

    cin >> n >> m;
    for(int i = 0; i < n; ++i){
        for(int j = 0; j < m; ++j){
            cin>>G[i][j];
        }
    }
    for(int i = 0; i < n; ++i){
        for(int j = 0; j < m; ++j){
            cout<<G[i][j];
        }
        cout<<endl;
    }

    start.x = 0;
    start.y = 0;
    start.level = 0;
    end.x = n - 1;
    end.y = m - 1;

    BFS();

    return 0;
}
    原文作者:迷宫问题
    原文地址: https://blog.csdn.net/void_worker/article/details/79751267
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞