广度优先搜索,也称为宽度优先搜索;
以一道走迷宫问题为例:
广度优先搜索是由入口处“一层一层”扩展到目标处,扩展时将发现的点放到队列中知道找到目标点为止
有n行m列的迷宫,现在需要从迷宫入口走到目标点,求最短步数。
第一行输入 n,m表示迷宫的行和列;
后面n行输入0或1,0表示空地,1表示障碍物,有障碍物的地方不能走;
最后一行输入迷宫入口坐标和目标点坐标;
#include<stdio.h>
struct note
{
int x;
int y;
int s;
};
int main ()
{
struct note que[2501];
int n,m,startx,starty,endx,endy,tx,ty,i,j,k,head,tail,flag;
int next[4][2]={ {1,0},{0,1},{-1,0},{0,-1}};
int a[51][51],book[51][51]={0};
scanf("%d %d",&n,&m);
for(i = 1; i <= n; i ++)
for(j = 1; j <= m; j ++)
scanf("%d",&a[i][j]);
scanf("%d %d %d %d",&startx,&starty,&endx,&endy);
//队列初始化
head=1;//对列头
tail=1;//队列尾
//把迷宫入口坐标插入队列
que[tail].x =startx;
que[tail].y =starty;
que[tail].s =0;
tail++;
book[startx][starty]=1;
flag=0;//用来标记是否达到终点 ,1表示到达,0表示未到达
//队列不为空是就循环
while(head<tail)
{
for(k = 0 ; k < 4 ; k ++)
{
tx=que[head].x +next[k][0];
ty=que[head].y +next[k][1];
//是否越界
if(tx<1 || tx>n || ty<1 || ty>m)
continue;
//是否遇到障碍物或已在路径中
if(a[tx][ty]==0 && book[tx][ty]==0)
{
//标记这个点,并插入到队列中
book[tx][ty]=1;
que[tail].x =tx;
que[tail].y =ty;
que[tail].s =que[head].s +1;//head是tail的上一步,是上一步的步数+1
tail++;
}
//到目标点就退出循环
if(tx==endx && ty==endy)
{
flag=1;
break;
}
}
if(flag==1)
break;
head++;//当一个点扩展结束后,head++才能对下一个点进行再扩展
}
//tail指向队尾的下一个位置,所以需要-1
printf("%d",que[tail-1].s );
return 0;
}
/*样例输入:
5 4
0 0 1 0
0 0 0 0
0 0 1 0
0 1 0 0
0 0 0 1
1 1 4 3
运行结果:
7
*/