小迷宫(BFS)

n行m列

题解:bfs,注释已经很清楚了

#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
typedef long long ll;
#define maxn 10005
#define mod 7654321
/* 迷宫最短路径,*为墙,S为起点,T为终点。 5 6 ....S* .**... .*..*. *..**. .T.... */
int n,m;
string maze[maxn];//迷宫
bool vis[maxn][maxn];//标记
int dir[4][2]={{0,1},{0,-1},{-1,0},{1,0}};//上下左右四个方向

bool in(int x,int y)//判断是否在地图范围内
{
    return 0<=x&&x<n&&0<=y&&y<n;
}

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]=true;
    while(!q.empty())
    {
        node now=q.front();//拿出队头
        q.pop();//队头出队
        for(int i=0;i<4;i++)//找下一层(上下左右)
        {
            int tx=now.x+dir[i][0];
            int ty=now.y+dir[i][1];
            if(in(tx,ty)&&maze[tx][ty]!='*'&&!vis[tx][ty])//判断此时坐标是否在地图内, 是否是墙,是是否访问过 //是否是墙,是否访问过
            {
                if(maze[tx][ty]=='T')//到达终点则return此时步数
                {
                    return now.d+1;
                }
                else
                {
                    vis[tx][ty]=true;//否则标记为访问过
                    q.push(node(tx,ty,now.d+1));//压入队列
                }
            }
        }
    }
    return -1;//遍历完所有层,没找到终点则返回-1
}

int main()
{
    cin>>n>>m;

    for(int i=0;i<n;i++)//输入迷宫
        cin>>maze[i];
    int x,y;
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
            if(maze[i][j]=='S')//找到迷宫开头
            {
                x=i;
                y=j;
            }
        }
    }

    cout<<bfs(x,y)<<endl;//地毯式搜索及输出

    return 0;
}

全部评论

相关推荐

牛客83700679...:简历抄别人的,然后再投,有反馈就是简历不行,没反馈就是学历不行,多投多改只要技术不差机会总会有的
点赞 评论 收藏
分享
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-08 10:39
一个证都没&nbsp;我能填什么
程序员小白条:别人有,你为什么没有,还是这个道理,社会就是比较,竞争,淘汰,你要安逸,那么就要做好淘汰的准备
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务