nyoj54 最少步数 搜索BFS 入门题

#include<stdio.h>
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
int a[9][9]=
{
    1,1,1,1,1,1,1,1,1,  
    1,0,0,1,0,0,1,0,1,  
    1,0,0,1,1,0,0,0,1,  
    1,0,1,0,1,1,0,1,1,  
    1,0,0,0,0,1,0,0,1,  
    1,1,0,1,0,1,0,0,1,  
    1,1,0,1,0,1,0,0,1,  
    1,1,0,1,0,0,0,0,1,  
    1,1,1,1,1,1,1,1,1
};


int b[4]={-1,1,0,0};
int c[4]={0,0,-1,1};
int visit[9][9];


struct node
{
int x,y;
int step;
};




int bfs(int x1,int y1,int x2,int y2)
{
int i,s,t;
node e={x1,y1,0};//新建结构体并赋初值 
queue<node>Q;
Q.push(e);
visit[x1][y1]=1;
while(!Q.empty())
{
e=Q.front();
if(e.x==x2&&e.y==y2)
break;
Q.pop();
for(i=0;i<4;i++)
{
s=e.x+b[i];
t=e.y+c[i];
if(s>=0&&s<=8&&t>=0&&t<=8&&!visit[s][t]&&a[s][t]==0)
{
node e1={s,t,e.step+1};
Q.push(e1);
visit[s][t]=1;
}
}
}
if(Q.empty())//进入了死胡同,说明无法到达 
return -1;
while(!Q.empty())//如果队列不为空 
Q.pop();//清空队列,以便再次使用 
return e.step;
}




int main()
{
int k,s,x1,x2,y1,y2;
scanf("%d",&s);
while(s--)
{
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
memset(visit,0,sizeof(visit));
k=bfs(x1,y1,x2,y2);
printf("%d\n",k);
}
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值