bfs走出迷宫



#include <iostream>

#include <queue> 
using namespace std;
struct node{
int x,y,step;
};
queue<node> Q;
int m,n;
const int maxn=200;
char map[maxn][maxn];
bool book[maxn][maxn]={false};
int next[4][2]={
0,-1,
0,1,
-1,0, 
1,0
};
int bfs(int x,int y,int endx,int endy){
node nn;
nn.x=x; nn.y=y; nn.step=0;
while(!Q.empty()) Q.pop();
Q.push(nn);
book[x][y]=true;
while(!Q.empty()){
node top;
top=Q.front();
Q.pop();
for(int i=0;i<4;i++){
int nx=top.x+next[i][0];
int ny=top.y+next[i][1];
if(nx<0 || nx>n-1 || ny<0 || ny>m-1) continue;
if(map[nx][ny]=='*')    continue;
if(book[nx][ny]==true)  continue;
node now;
now.x=nx;  now.y=ny;  now.step=top.step+1;
if(nx==endx  &&  ny==endy)  return now.step;
Q.push(now);
book[nx][ny]=true;


}
int main(int argc, char** argv) {
cin>>m>>n;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
cin>>map[i][j];
}
}
int startx,starty,endx,endy;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(map[i][j]=='S'){
startx=i;
starty=j;
}
if(map[i][j]=='T'){
endx=i;
endy=j;
}
}
}
int ans;
cout<<startx<<" "<<starty<<endl;
cout<<endx<<" "<<endy<<endl;
ans=bfs(startx,starty,endx,endy);
cout<<ans<<endl;
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值