BFS模板

《BFS模板》

 

《BFS模板》
《BFS模板》

#include <stdio.h>
#include <string.h>
#include <queue>

using namespace std;

#define MAXN 1005

struct node
{
    int x;
    int y;
    int step;
};

char maps[MAXN][MAXN];
char vis[MAXN][MAXN];
int to[4][2]= {{-1,0},{1,0},{0,1},{0,-1}};
int r,c;
int sx,sy;  ///起点
int ans;

int check(int x,int y)
{
    if(x<0||x>=r||y<0||y>=c)
        return 1;
    if(vis[x][y]||maps[x][y]=='#')
        return 1;
    return 0;
}

void bfs()
{
    queue<node>Q;
    node a,next;
    a.x=sx;
    a.y=sy;
    a.step=0;
    vis[a.x][a.y]=true;
    Q.push(a);
    while(!Q.empty())
    {
        a=Q.front();
        Q.pop();
        if(maps[a.x][a.y]=='E')
        {
            ans=a.step;
            return;
        }
        for(int i=0; i<4; i++)
        {
            next=a;
            next.x+=to[i][0];
            next.y+=to[i][1];
            if(check(next.x,next.y))
                continue;
            next.step=a.step+1;
            vis[next.x][next.y]=true;
            Q.push(next);
        }
    }
    ans=-1;
}

int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&r,&c);
        for(int i=0; i<r; i++)
        {
            scanf("%s",maps[i]);
            for(int j=0; j<c; j++)
            {
                if(maps[i][j]=='S')
                {
                    sx=i;
                    sy=j;
                }
            }
        }

        memset(vis,false,sizeof(vis));
        bfs();
        printf("%d\n",ans);
    }
    return 0;
}

View Code

 

    原文作者:小草的大树梦
    原文地址: https://www.cnblogs.com/TreeDream/p/5402561.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞