2019蓝桥c语言b组迷宫!!!!

 迷宫这种刷了多少次的题还没过,诶,回家还是发现结构体理解不够深刻,说说自己为什么没做出来

以下是hdu迷宫代码,类似于本题

#include "iostream"
#include "queue"
#include "cstring"
#include "stdlib.h"
using namespace std;
struct point{
    int x,y;
    int step;
    point *pre;
    point(){
    }
    point(int a,int b,int c){
        x=a,y=b;
        step=c;
    }
};
int maze[100][100];
int book[100][100];
int next[4][2]={0,1,1,0,-1,0,0,-1};
int n;
queue<point *> que;
point* bfs(int x,int y){
    point* start = new point(1,1,0);

//new和malloc均可,更好的方式是使用point数组寻址,并不会释放内存!!!

//使用 point start(1,1,0);这种方式问题很大,寻址的时候point变量会被全部释放

//使用 point start(1,1,0);这种方式问题很大,寻址的时候point变量会被全部释放

//使用 point start(1,1,0);这种方式问题很大,寻址的时候point变量会被全部释放

//重要事情说三遍

//这样的输出的路径是反过来的,只需要通过stack的操作逆过来就行了!!!!


    point* end = new point(n,n,0);
    que.push(start);
    book[start->x][start->y]=1;
    start->pre=NULL;
    while(!que.empty()){
        point* cur = que.front();
        que.pop();
        if(cur->x==end->x&&cur->y==end->y){
            cout<<cur->step<<endl;
            return cur;
        }
        for(int i=0;i<=3;i++){
            point* tmp=(point *)malloc(sizeof(point));
            tmp->x=cur->x+next[i][0];
            tmp->y=cur->y+next[i][1];
            tmp->step=cur->step+1;
            if(tmp->x>=1&&tmp->y>=1&&tmp->x<=n&&tmp->y<=n&&maze[tmp->x][tmp->y]==0&&book[tmp->x][tmp->y]==0){
                que.push(tmp);
                tmp->pre=cur;
                book[tmp->x][tmp->y]=1;
            }
        }
    }
    
}
void print(){
    point* q=bfs(1,1);
    while(q->pre!=NULL){
        cout<<q->x<<","<<q->y<<endl;
        q=q->pre;
    }
}
int main(){
    
    cin>>n;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            cin>>maze[i][j];
        }
    }
    print();
    return 0;
}

发布了40 篇原创文章 · 获赞 24 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_41466575/article/details/88824351