BFS——POJ 3984 走迷宫➕保存路径

#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<queue>
#include<vector>
#include<string>
#define M 200000010
#define INF 0x3f3f3f3f
using namespace std;

struct node{
    int x,y;
};          //记录点的坐标信息
int mp[10][10];         //记录地图
bool vis[10][10];       //记录是否走过
int nex[4][2]={0,1,0,-1,1,0,-1,0};
struct node last[10][10];       //保存上一步的坐标
queue<node>q; //里面需要是结构体,因为要存一个点的坐标

void print(int x,int y){
    if(x==0&&y==0){
        printf("(%d, %d)\n",x,y);
        return ;
    }
    node fa = last[x][y];
    print(fa.x,fa.y);
    printf("(%d, %d)\n",x,y);
}       //递归打印,从最后一点开始往前推

int main()
{
    
    for(int i=0; i<5; i++){
        for(int j=0; j<5; j++){
            scanf("%d",&mp[i][j]);
        }
    }
   
    struct node t;
    t.x = 0; t.y = 0;
    q.push(t);           //从左上角开始走
    vis[0][0] = 1;
    //广搜
    while(!q.empty()){
        t = q.front();      //t保存弹出的队首
        q.pop();
        for(int i=0; i<4; i++){
            int xx = t.x + nex[i][0];
            int yy = t.y + nex[i][1];
            //先判断坐标范围,否则段错误
            if(xx>=0&&xx<5 && yy>=0&&yy<5 && !vis[xx][yy] && mp[xx][yy]==0){
                struct node tt;
                tt.x = xx; tt.y = yy;
                q.push(tt);             //这一点入队
                vis[xx][yy] = 1;        //这一点标记
                last[xx][yy] = t;       //保存这一点的前一步
            }
        }
    }
    //打印路径
    print(4,4);
    return 0;
}

发布了30 篇原创文章 · 获赞 0 · 访问量 681

猜你喜欢

转载自blog.csdn.net/jhckii/article/details/104128925
今日推荐