广度优先搜索(迷宫问题从 start_x,starty----->endX,endY)

留下空白 注释 日后加 



#include<stdio.h>
#include<stdlib.h>
int a[10][10]={
                {0,0,1,0},
                {1,1,1,1},
                {0,0,1,0},
                {0,1,0,0},
                {0,0,0,1}
                };
int book[10][10];
typedef struct Node
{
    int col;
    int row;
    int step;
    struct Node* next;
}Node;
typedef  struct Node Element;
typedef struct Queue
{
    Node *front;
    Node *tail;
} LinkQueue;//Node *front是因为front tail只是指示队列头尾的指针而已 而非实际节点
LinkQueue * init()
{
    LinkQueue* Q=(LinkQueue*)malloc(sizeof(Q));
    Q->front=Q->tail=NULL;
    return Q;
}
Node *Dequeue(LinkQueue *Q)
{
    Node *p =Q->front;
    if(p==NULL)
    {
        printf("nothing\n");
        return NULL;
    }
    if(Q->front!=Q->tail)
    {
        Q->front=p->next;

    }
    else
    {
        Q->front=Q->tail=NULL;
    }
     return p;
}
void Enqueue(LinkQueue *Q,Element *e)
{
    if(Q->tail==NULL)
    {
        Q->front = Q->tail=e;
       

    }
    else
    {
        Q->tail->next=e;
        Q->tail=e;
        //printf("second.... in\n");
    }
 
}

int main()
{
    int start_x,start_y;
    int tx,ty;
    int k;
    int next[4][2]={{0,1},
                    {1,0},
                    {0,-1},
                    {-1,0}};
    int flag=0;
    Node *p;
    LinkQueue* Q=init();
    scanf("%d%d",&start_x,&start_y);//0 0
    //printf("%d %d",start_x,start_y);
    int endX=3;
    int endY=2;
    Node* e=(Node*)malloc(sizeof(Node));
    e->col=start_x;
    e->row=start_y;
    e->step=0;
    book[start_x][start_y]=1;
    Enqueue(Q,e);


   while(Q->tail!=NULL)//队列非空
    {

        for(k=0;k<4;k++)//寻找下一个点
        {
            tx=Q->front->col+next[k][0];
            ty=Q->front->row+next[k][1];

            if(tx>=5||tx<0||ty>=4||ty<0)
                continue;
            if(a[tx][ty]==0&&book[tx][ty]==0)
            {
                Node* node=(Node*)malloc(sizeof(Node));
                node->col=tx;
                node->row=ty;
                node->step=Q->front->step+1;
             
                book[tx][ty]=1;
                Enqueue(Q,node);
            }
            if(tx==endX&&ty==endY)
            {
                 
                flag=1;
                break;
            }
        }
        if(flag==1)
        {
            printf("success\n");
            break;
        }
        else
        {

             p=Dequeue(Q);
            printf("[************%d\n",p->step);
        }
    }
    if(Q->tail==NULL&&flag==0)
    {
        printf("不能去哪里");
    }
   else
    printf("%d step",Q->tail->step);


    return  0;
}






评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值