计蒜客第三章:走迷宫2

计蒜客习题:走迷宫2

题目

在这里插入图片描述

样例

在这里插入图片描述

代码

#include<iostream>
#include<queue>
using namespace std;
int v[105][105],num[105][105],n,m,xx[7]={0,0,-1,1},yy[7]={1,-1,0,0};
char map[105][105];
struct point
{
    int x, y;
    point(int xx,int yy)
    {
        x=xx;
        y=yy;
    }
};
void bfs(int sx,int sy)
{
    queue<point> q;
    q.push(point(sx,sy));
    v[sx][sy]=1;
    while(!q.empty())
    {
        int x=q.front().x;
        int y=q.front().y;
        q.pop();
        for(int i=0;i<4;i++)
        {
            int tx=x+xx[i];
            int ty=y+yy[i];
            //cout<<tx<<" "<<ty<<endl;
            if(tx<1||tx>n||ty<1||ty>m) continue;
            if(!v[tx][ty]&&map[tx][ty]!='#')
            {
                v[tx][ty]=1;
                //cout<<tx<<" "<<ty<<endl;
                num[tx][ty]=num[x][y]+1;
                if(map[tx][ty]=='T') return;
                q.push(point(tx, ty));
            }
        }
    }
    return;
}

int main()
{
    int sx,sy,ex,ey;
    cin>>n>>m;
    getchar();
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++)
        {
            cin>>map[i][j];//cout<<map[i][j];
            if(map[i][j]=='S') {sx=i;sy=j;}
        	if(map[i][j]=='T') {ex=i;ey=j;}
        }
    //cout<<sx<<sy<<endl;
	bfs(sx,sy);
    if(num[ex][ey]) cout<<num[ex][ey];
    else cout<<"-1";
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值