zoukankan      html  css  js  c++  java
  • (bfs入门)走迷宫

    题意:给一个n*m的二维数组,S表示入口,T表示出口,*点表示墙不可达,. 表示路可达。

              求S走到到T的最短距离。

    输入样例:

    5 6
    ....S*
    .**...
    .*..*.
    *..**.
    .T....

    输出样例:

    7

    #include <cstdio>
    #include <string.h>
    #include <iostream>
    #include <algorithm>
    #include <sstream>
    #include <math.h>
    #include <queue>
    using namespace std;
    const int inf=0x7fffffff;
    const long long mod=1e9+7;
    const double PI=acos(-1);
    
    int n,m;
    int ans;
    bool vis[105][105];
    char a[105][105];
    int next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};//四个方向
    bool in(int x,int y){
        return x>=0&&x<n&&y>=0&&y<m;
    }
    struct node{
        int x,y,d;
        node(int xx,int yy,int dd){
            x=xx;
            y=yy;
            d=dd;
        }
    };
    int bfs(int sx,int sy){
        queue<node> q;
        q.push(node(sx,sy,0));
        vis[sx][sy]=1;
        while(!q.empty()){                                     //bfs核心就是不断出队入队 
            node now = q.front();
            q.pop();
            for(int i=0;i<4;i++){                               //依此遍历每个节点的四个方向 
                int tx=now.x+next[i][0];
                int ty=now.y+next[i][1];
                if(in(tx,ty)&&a[tx][ty]!='*'&&!vis[tx][ty]){
                    if(a[tx][ty]=='T'){                          //找到出口 返回 
                        return now.d+1;
                    }
                    else{                                        //非出口 将该节点入队 
                        vis[tx][ty]=1;
                        q.push(node(tx,ty,now.d+1));
                    }
                }
            }
        }
        return -1;
    }
    int main()
    {
        cin>>n>>m;
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                cin>>a[i][j];
            }
        }
        int x,y;
        for(int i=0;i<n;i++){                                   //找入口
            for(int j=0;j<m;j++){
                if(a[i][j]=='S') x=i,y=j;
            }
        }
        cout<<bfs(x,y);
        return 0;
    }
  • 相关阅读:
    Vue学习笔记(4)-带参数路由,嵌套路由,编程式导航
    JS数组&&数组对象去重
    Vue学习笔记(3)-品牌管理系统
    Vue学习笔记(2)-组件生命周期
    负margin
    CSS布局奇淫巧计之-强大的负边距
    由浅入深漫谈margin属性
    双飞翼布局和圣杯布局的对比
    圣杯布局的实现过程
    CSS实现垂直居中的5种方法
  • 原文地址:https://www.cnblogs.com/xusi/p/12572707.html
Copyright © 2011-2022 走看看