0
点赞
收藏
分享

微信扫一扫

数据结构线性结构(二)6迷宫最短路径

中间件小哥 2023-10-29 阅读 55

 

 

#include <iostream>
#include<queue>

using namespace std;
int dir[8][2]={{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1}};
int map_[1010][1010];
int sx,sy,ex,ey;
void BFS(int x,int y);
void outPath();
struct Node{
    int x,y;
    Node(int x=0,int y=0){
        this->x=x;
        this->y=y;
    }
};
Node **path;
queue<Node> q;
int main()
{
    int x,y;
    cin>>x>>y;
    sx=0;
    sy=0;
    ex=x-1;
    ey=y-1;
    path=new Node *[x];

    for(int i=0;i<x;i++)
    {
        path[i]=new Node[y];

        for(int j=0;j<y;j++) {
            cin>>map_[i][j];
            path[i][j]=Node(0,0);
        }
    }


    BFS(sx,sy);
    outPath();
    return 0;
}

void BFS(int x,int y)
{
    //queue<pair<int,int>> q;
    q.push(Node(x,y));
    while(!q.empty()) {
        Node p=q.front();
        q.pop();
        if(p.x==ex&&p.y==ey) {
            return;
        }
        for(int i=0;i<8;i++) {
            int nx=p.x+dir[i][0];
            int ny=p.y+dir[i][1];
            if(nx<0||nx>=ex+1||ny<0||ny>=ey+1||map_[nx][ny]==1) {
                continue;
            }
            path[nx][ny]=p;
            q.push(Node(nx,ny));
            map_[nx][ny]=1;
        }
    }
    cout<<path[ex][ey].x<<endl;
}

void outPath()
{
    int p=ex,q=ey;
    cout<<"("<<ex+1<<","<<ey+1<<")"<<endl;

    //cout<<path[p][q].x<<endl;
    while(path[p][q].x!=sx||path[p][q].y!=sy ) {
        cout<<"("<<path[p][q].x+1<<","<<path[p][q].y+1<<")"<<endl;
        int t=p;
        p=path[p][q].x;
        q=path[t][q].y;
    }
    cout<<"("<<sx+1<<","<<sy+1<<")"<<endl;
}

/*
6 8
0 1 1 1 0 1 1 1
1 0 1 0 1 0 1 0
0 1 0 0 1 1 1 1
0 1 1 1 0 0 1 1
1 0 0 1 1 0 0 0
0 1 1 0 0 1 1 0
*/
举报

相关推荐

0 条评论