啊哈,算法自學記——7th

小哈迷宮搜救記之——

廣度優先搜索

在這裏插入圖片描述

在這裏插入圖片描述
在這裏插入圖片描述

#include <stdio.h>

typedef struct note
{
    int x;
    int y;
    int step;
};


int main(int argc, char const *argv[])
{
    struct note que[2501];//因爲地圖大小不會超過50*50,所以地圖擴展不過超過2500
    int a[51][51]={0};//存儲地圖
    int book[51][51]={0};//標記已經走過的路線

    int next[4][2]={
        {0,+1},//you
        {+1,0},//xia
        {0,-1},//zuo
        {-1,0}//shang
    };

    int head,tail;
    int n,m,flag,xstart,ystart,p,q,tx,ty;

    printf("Read The Map:\r\n");
    printf("Input the size of the map:\r\n");
    scanf("%d %d",&n,&m);
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= m; j++)
        {
            scanf("%d",&a[i][j]);
        }
    }
    
    printf("Input the xstart ystart and xend yend:\r\n");
    scanf("%d %d %d %d",&xstart,&ystart,&p,&q);

    //隊列初始化
    head=1;
    tail=1;
    //往隊列中插入地圖入口座標
    que[tail].x=xstart;
    que[tail].y=ystart;
    que[tail].step=0;
    tail++;
    book[xstart][ystart]=1;//標記起點已在路徑中

    flag=0;//表示暫時沒有到達目標點

    //當隊列不爲空的時候循環
    while (tail>head)
    {
        for (int i = 0; i <= 3; i++)
        {
            //計算下一個點的座標
            tx=que[head].x+next[i][0];
            ty=que[head].y+next[i][1];

            //判斷是否越界
            if(tx<1||ty<1||tx>n||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].step=que[head].step+1;
                tail++;
            }

            if (tx==p && ty==q)
            {
                flag=1;
                break;
            }
            
        }
        
        if (flag==1)
        {
            break;
        }
        head++;//當一個點擴展結束後,head++才能對後面的點進行擴展
    }
    

    printf("%d",que[tail-1].step);

    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章