POJ-3984 迷宫问题

POJ-3984 迷宫问题

题目链接:POJ-3984
在这里插入图片描述
题目大意:求从图左上角到右下角的最短路径

解题思路:bfs 需要按顺序输出这是个要注意的点 我用的是结构体储存前面的节点 最后输出之前 将前面的节点一个个压入栈 然后弹出输出就好了 注意 往队列里添加数据的时候 记得把走过的点全部改为1 否则指针会乱掉

代码块:

#include<iostream>
#include<queue>
#include<stack>
#include<map>

using namespace std;
typedef struct node{
    int x;
    int y;
    struct node *pre;
}myNode;
typedef myNode *pNode;
int arrA[6][6];
int xxx[4]= {0,1,0,-1};
int yyy[4]= {1,0,-1,0};

void bfs(int x, int y);
int main() {
    for(int i=0; i<5; i++) {
        for(int j=0; j<5; j++) {
            cin>>arrA[i][j];
        }
    }
    bfs(0,0);
    return 0;
}
void bfs(int x, int y) {
    queue<myNode> queueA;
    myNode n1;
    n1.x = x;
    n1.y = y;
    n1.pre = NULL;
    queueA.push(n1);
    while(queueA.size()) {
        if(queueA.front().x == 4 && queueA.front().y == 4){
            stack<myNode> stackA;
            pNode nowNode = &queueA.front();
            while(nowNode->pre != NULL){
                stackA.push(*nowNode);
                nowNode = nowNode->pre;
            }
            stackA.push(*nowNode);
            while(stackA.size()){
                cout<<"("<<stackA.top().x<<", "<<stackA.top().y<<")"<<endl;
                stackA.pop();
            }
        }
        for(int i=0; i<4; i++) {
            int xx = queueA.front().x + xxx[i];
            int yy = queueA.front().y + yyy[i];
            if(xx >= 0 && xx <5 && yy >= 0 && yy <5 && arrA[xx][yy] == 0){
                n1.x = xx;
                n1.y = yy;
                n1.pre = &queueA.front();
                queueA.push(n1);
                arrA[xx][yy] = 1;
            }
        }
        queueA.pop();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值