迷宫+bfs经典写法

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

int n,m,num,sx,sy,ex,ey;
int foot[4][2]={-1,0,1,0,0,-1,0,1};
char a[510][510];
bool p[510][510];

struct node
{
    int ti,x,y,cnt;
};
queue<node>q;

void bfs()
{
    node w;
    w.x=sx;w.y=sy;w.ti=0;w.cnt=5;
    q.push(w);
    p[sx][sy]=1;
    w=q.front();
    while (w.x!=ex || w.y!=ey)
    {

        for (int i=0;i<4;i++)
        {
            int x=w.x+foot[i][0],y=w.y+foot[i][1];

            if (a[x][y]!='#' && p[x][y]==0)
            {
                p[x][y]=1;
                node s;
                s.x=x;s.y=y;s.ti=w.ti+1;s.cnt=w.cnt;
                q.push(s);
            }
        }
        int x=(n+1)-w.x,y=(m+1)-w.y;
        if (w.cnt>0)
        if (a[x][y]!='#' && p[x][y]==0)
        {
            p[x][y]=1;
            node s;
            s.x=x;s.y=y;s.ti=w.ti+1;s.cnt=w.cnt-1;
            q.push(s);
        }
        q.pop();
        if (q.empty()) break;
        w=q.front();
    }
    if (!q.empty()) cout<<w.ti<<endl;
             else   cout<<"-1"<<endl;
}


int main()
{

    cin>>n>>m;
    for (int i=1;i<=n;i++)
    {
        for (int j=1;j<=m;j++)
        {
            cin>>a[i][j];
            if (a[i][j]=='S') {sx=i;sy=j;}
            else if (a[i][j]=='E') {ex=i;ey=j;}
        }
        getchar();
    }
    for (int i=1;i<=n;i++)
    {
        a[i][0]='#';
        a[i][m+1]='#';
    }
    for (int j=1;j<=m;j++)
    {
        a[0][j]='#';
        a[n+1][j]='#';
    }
    while (!q.empty()) q.pop();//先清空队列
    memset(p,0,sizeof(p));
    bfs();

    return 0;
}

猜你喜欢

转载自blog.csdn.net/hbhhhxs/article/details/105056877