广搜BFS 迷宫问题

2021年9月18日 2点热度 0条评论 来源: bmxklYzj

广搜BFS 迷宫问题

//@auther Yang Zongjun
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string>
#include <queue>

using namespace std;
#define PI acos(-1.0)
#define EPS 1e-8
const int MAXN = 105;
const int INF = 2100000000;
char maze[MAXN][MAXN];
int d[MAXN][MAXN];
int n, m, sx, sy, gx, gy;
int dx[] = {0, 1, 0, -1};
int dy[] = {1, 0, -1, 0};

typedef pair<int, int > P;

int bfs()
{
    queue<P> que;
    que.push(P(sx, sy));
    d[sx][sy] = 0;
    while(que.size())
    {
        P p = que.front();
        que.pop();
        if(p.first == gx && p.second == gy) break;
        for(int i = 0; i < 4; i++)
        {
            int nx = p.first + dx[i], ny = p.second + dy[i];
            if(0 <= nx && nx < n && 0 <= ny && ny < m && maze[nx][ny] != '#' && d[nx][ny] == INF)
            {
                que.push(P(nx, ny));
                d[nx][ny] = d[p.first][p.second] + 1;
            }
        }
    }
    return d[gx][gy];
}

int main()
{
    freopen("C:/Users/Administrator/Desktop/input.txt", "r", stdin);
    scanf("%d%d", &n, &m);
    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < m; j++)
        {
            scanf("%c", &maze[i][j]);
        }
        getchar();
    }
    for(int i =0; i < n; i++)
    {
        for(int j =0; j < m; j++)
        {
            if(maze[i][j] == 'S')
            {
                sx = i; sy = j;
            }
            if(maze[i][j] == 'G')
            {
                gx = i; gy = j;
            }
        }
    }
    for(int i = 0; i< n; i++)
        for(int j = 0; j < m; j++)
        d[i][j] = INF;
    printf("%d\n", bfs());
    return 0;
}
/*
10 10
#S######.#
......#..#
.#.##.##.#
.#........
##.##.####
....#....#
.#######.#
....#.....
.####.###.
....#...G#
*/

    原文作者:bmxklYzj
    原文地址: https://blog.csdn.net/yang_zongjun/article/details/39103039
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。