zoukankan      html  css  js  c++  java
  • 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
    ",ans);
        }
        return 0;
    }
    View Code
  • 相关阅读:
    LOAD XML
    LOAD DATA
    INSERT 插入语句
    keras第一课
    android系统开发之开启启动
    Qt使用数据库
    微信订阅号案例之一
    python_install
    QtObject使用
    Qml_JS文件的使用
  • 原文地址:https://www.cnblogs.com/TreeDream/p/5402561.html
Copyright © 2011-2022 走看看