广度优先遍历

来源:互联网 发布:php curl 编码 编辑:程序博客网 时间:2024/05/20 03:08


还是上面那道题:
深度遍历一般是用递归,深度不断增加,广度搜索一般用队列这样的形式存储东西;

#include <iostream>#include <cstdio>using namespace std;struct note{    int x;    int y;    int f;    int s};int main(){    struct note que[2501]; //用一个数组当一个队列    int a[51][51] = {0},book[51][51]={0};    int next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};    int head,tail;    int i,j,k,n,m,startx,starty,p,q,tx,ty,flag;    scanf("%d %d",&n,&m);    for(int i=1;i<=n;i++)        for(int j=1;i<=m;j++)            scanf("%d",&a[i][j]);    scanf("%d %d %d %d",&startx,&starty,&p,&q);    //队列初始化    head = 1;    tail = 1;    que[tail].x = startx;    que[tail].y = starty;    que[tail].f = 0;//输出路径用的    que[tail].s = 0;    tail++;    book[startx][starty] = 1;    flag = 0;    while(head < tail)    {        for(k=0;k<=3;k++)        {            tx = que[head].x+next[k][0];            ty = que[head].y+next[k][1];            if(tx < 1 || ty >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].f = head; //因为这个点是从head出来的,所以他的父亲就是head                que[tail].s = que[head].s+1;                tail++;            }            if(tx == p && ty == q)            {                flag = 1;                break;            }        }        if(flag == 1)            break;        head++;    }    printf("%d",que[tail-1].s);    getchar();    return 0;}
0 0