POJ 3984 Labyrinth Problem (BFS Wide Search)

The topic is posted:
Insert picture description here
Compared with the topic of finding the shortest path length, this topic may be a little bit more difficult, because it requires the output of all the shortest path points.
Idea: Define a structure with the x, y coordinates of the traversal point at this time and the The parent point of the point (meaning your last state), for example, a path is (0,0)->(1,1)->(2,2), then the parent point of the point (2,2) is ( 1,1), we will output the points with the father point, and the points without the father point will not be output. The following is the code. In order to prevent repeated traversal of a certain point, add a visit mark

// YSJ 2020-11-1---18:05
#include<iostream>
#include<cstdio>
using namespace std;
//const int MAX = 1e6+20;
int dir_x[4]={
    
    0,-1,1,0};//down,left,right,up
int dir_y[4]={
    
    1,0,0,-1};
struct Node{
    
    
    int x,y,pre;
}Queue[30];
int front = 0,rear = 0;
int a[8][8],visit[8][8];
void BFS(int Bx,int By,int Ex,int Ey)
{
    
    
    Queue[0].x = Bx;
    Queue[0].y = By;
    Queue[0].pre = -1;
    ++rear;
    visit[Bx][Bx]=1;
    while(front < rear){
    
    
        for(int i=0;i<4;++i){
    
     //上 ,下 ,左,右四个方向判断
           int newx = Queue[front].x + dir_x[i];
           int newy = Queue[front].y + dir_y[i];
           if(newx<1||newy<1||newx>5||newy>5||visit[newx][newy]||a[newx][newy]==1)
                continue;
           //否则,进队
           Queue[rear].x = newx;
           Queue[rear].y = newy;
           Queue[rear].pre = front;
           ++rear;
           visit[newx][newy] = 1;
           if(newx == Ex && newy == Ey)
                return;
        }
        ++front;
    }
}

void Print_Path(Node now) //下面减1的原因是我的数组下标是从1开始的,
//题目是从0开始的
{
    
    
    if(now.pre==-1){
    
    
        printf("(%d, %d)\n",now.x-1,now.y-1);
    }else{
    
    
        Print_Path(Queue[now.pre]);//这里寻求父亲点,有点并查集的味道
        printf("(%d, %d)\n",now.x-1,now.y-1);
    }
}

int main(void)
{
    
    
    int t;
    for(int i=1;i<=5;++i)
        for(int j=1;j<=5;++j)
            cin>>a[i][j];
    BFS(1,1,5,5);
    Print_Path(Queue[rear-1]);
}

Guess you like

Origin blog.csdn.net/YSJ367635984/article/details/109432665