bfs 迷宫输出最短路径

想法:用step[maxn][maxn]数组储存每个位置需要的最小步数
用dir[maxn][maxn]存储上个节点过来的方向,由于是bfs,到这个位置的时候如果步数最小,那么方向一定是唯一的。所以每个位置的dri只会被更新一次
还需要一个visit数组储存是否访问(也可以把map设置成false,因为一个地方被visit以后相当于这里就是墙了)

注意这里涉及到deque的使用,
deque有
push_back
,push_front,
pop_back,
pop_front,
back,
front方法

#include <iostream>
#include <queue>
#include <deque>
using namespace std;
int sx,sy,dx,dy;
const int maxn=10005;
bool visit[maxn][maxn];
int dir[maxn][maxn];
bool map[maxn][maxn];
int step[maxn][maxn];
int M,N;
const int INF=999999;
int tx[]={0,0,-1,1};
int ty[]={-1,1,0,0};
typedef struct{
    int x,y;
}Point;
int bfs(int x,int y){
    visit[x][y]=true;
    queue<Point> Q;
    Point cur;
    cur.x=x,cur.y=y;
    Q.push(cur);
    while(!Q.empty()){
        cur=Q.front();
        Q.pop();
        if(cur.x==dx&&cur.y==dy) return step[cur.x][cur.y];
        Point next;
        for(int i=0;i<4;i++){
            next.x=cur.x+tx[i],next.y=cur.y+ty[i];
            if(map[next.x][next.y]&&!visit[next.x][next.y]){
                Q.push(next);
                visit[next.x][next.y]=true;
                dir[next.x][next.y]=i+1;
                step[next.x][next.y]=step[cur.x][cur.y]+1;
            }
        }
    }
    return INF;
}

void print(int x,int y){
    deque<Point> path;
    Point next;
    while(x!=sx||y!=sy){
        next.x=x,next.y=y;
        path.push_back(next);
        if(dir[x][y]==1) y++;
        else if(dir[x][y]==2) y--;
        else if(dir[x][y]==3) x++;
        else if(dir[x][y]==4) x--;
        else return ;
    }
    next.x=sx,next.y=sy;
    path.push_back(next);
    while(!path.empty()){
        next=path.back();
        path.pop_back();
        printf("(%d,%d)\n",next.x,next.y);
    }
}

int main(int argc, char const *argv[])
{
    while(cin>>M>>N){
        memset(map,false,sizeof(map));
        memset(dir,0,sizeof(dir));
        memset(visit,false,sizeof(visit));
        for(int i=1;i<=M;i++){
            for(int j=1;j<=N;j++){
                cin>>map[i][j];
            }
        }
        cin>>sx>>sy>>dx>>dy;
        cout<<bfs(sx,sy)<<endl;;
         print(dx,dy);
        // for(int i=1;i<=M;i++){
        //  for(int j=1;j<=N;j++){
        //      cout<<dir[i][j]<<" ";
        //  }
        //  cout<<endl;
        // }
        // cout<<endl;
        // for(int i=1;i<=M;i++){
        //  for(int j=1;j<=N;j++){
        //      cout<<map[i][j]<<" ";
        //  }
        //  cout<<endl;
        // }
        // cout<<endl;
        // for(int i=1;i<=M;i++){
        //  for(int j=1;j<=N;j++){
        //      cout<<step[i][j]<<" ";
        //  }
        //  cout<<endl;
        // }
        // cout<<endl;
    }
    /* code */
    return 0;
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值