迷宫广搜

本文介绍了一个使用C++实现的迷宫最短路径寻找算法,通过BFS(宽度优先搜索)来解决给定起点到终点是否可达的问题,并在可达的情况下判断是否能在限定步数内到达。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
#include<queue>
using namespace std;

int T,M,N,k,sx,sy,ex,ey;
char map[101][101];
bool f[101][101];
int dir[4][2] = {1,0,-1,0,0,1,0,-1};

struct node
{
    int x,y;
 int step;
}s,e;
queue<node>q;

void init()
{
    memset(f,false ,sizeof(f));
    while(!q.empty()) 
  q.pop();
    memset(map,0,sizeof(map));
}

bool is_ok(int x, int y)
{
    if(x>=1 && x<=M && y>=1 && y<=N &&  map[x][y] == '.') 
  return true;
    return false;
}

void BFS()
{
    if(sx == ex && sy == ey)
    {
        cout<<"yes"<<endl;
        return ;
    }
    f[sx][sy] = true;
    s.x = sx; s.y = sy ; s.step = -1;
    q.push(s);
    while(!q.empty())
    {
        s = q.front();
        q.pop();
        for(int i=0;i<4;i++)
        {
            int xx = s.x + dir[i][0];
            int yy = s.y + dir[i][1];
            while(is_ok(xx,yy))
            {
               if(f[xx][yy]==false)
               {
                    f[xx][yy] = true;
                    e.x = xx;
                    e.y = yy;
                    e.step = s.step+1;
                    q.push(e);
                    if(e.x == ex && e.y == ey && e.step <=k)
                     {
                            cout<<"yes"<<endl;
                            return ;
                     }
                }
                xx += dir[i][0];
                yy += dir[i][1];
            }
        }
      }
    cout<<"no"<<endl;
    return ;
}

int main()
{
 int i,j;
 freopen("D:\\input.txt","r",stdin);
 cin>>T;
 while(T--)
 {    
   init();
      cin>>M>>N;
   for(i=1;i<=M;i++)
    for(j=1;j<=N;j++)
    {
      cin>>map[i][j];
    }
      cin>>k>>sy>>sx>>ey>>ex;
   BFS();
 }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值