迷宮問題 (bfs廣度優先搜索記錄路徑)


  • 問題描述:

定義一個二維數組: 

int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};

它表示一個迷宮,其中的1表示牆壁,0表示可以走的路,只能橫着走或豎着走,不能斜着走,要求編程序找出從左上角到右下角的最短路線。

Input

一個5 × 5的二維數組,表示一個迷宮。數據保證有唯一解。

Output

左上角到右下角的最短路徑,格式如樣例所示。

Sample Input

0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0

Sample Output

(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)
  • 解題思路:

bfs,用pre記錄上一個位置,最后用回溯的方法輸出路徑。
  • 代碼:

#include<cstdio>
#include<queue>
#include<cstring>
#include<iostream>
using namespace std;
int b[6][6];
int a[6][6];
int next[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
struct node
{
    int x,y;
    int pre;
}que[510];
int tx,ty;

void print(int s)
{
    if(que[s].pre!=-1)
    {
        print(que[s].pre);
        printf("(%d, %d)\n",que[s].x,que[s].y);
    }
}

void bfs(int x,int y)
{
    int head=1,tail=1;
    que[tail].x=x;
    que[tail].y=y;
    que[tail].pre=-1;
    tail++;
    while(head<tail)
    {
        for(int i=0;i<4;i++)
        {
            tx=que[head].x+next[i][0];
            ty=que[head].y+next[i][1];
            if(tx<0||tx>=5||ty<0||ty>=5)continue;
            if(b[tx][ty]==0&&a[tx][ty]==0)
            {
                b[tx][ty]=1;
                que[tail].x=tx;
                que[tail].y=ty;
                que[tail].pre=head;
                tail++;
            }
            if(tx==4&&ty==4)
                print(head);
        }
        head++;
    }
}

int main()
{
    for(int i=0;i<5;i++)
    {
        for(int j=0;j<5;j++)
        {
            scanf("%d",&a[i][j]);
        }
    }
    memset(b,0,sizeof(b));
    b[0][0]=1;
    printf("(0, 0)\n");
    bfs(0,0);
    printf("(4, 4)\n");
    return 0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM