POJ 3984 迷宫问题 (BFS + Stack)

本文介绍了一种使用广度优先搜索(BFS)解决迷宫问题的方法,并详细阐述了如何记录路径,确保从终点回溯到起点的过程中正确输出经过的路径。通过定义迷宫地图并采用队列和栈来实现算法。

链接 : Here!

思路 : BFS一下, 然后记录下每个孩子的父亲用于找到一条路径, 因为寻找这条路径只能从后向前找, 这符合栈的特点, 因此在输出路径的时候先把目标节点压入栈中, 然后不断的向前寻找, 最后直接pop出栈中所有的元素即可.

注意 : 不要把局部变量压入栈中, 这样就直接段错误了◔ ‸◔


/*************************************************************************
    > File Name: 3984-迷宫问题.cpp
    > Author: 
    > Mail: 
    > Created Time: 2017年11月29日 星期三 19时28分22秒
 ************************************************************************/

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <stack>
using namespace std;

#define MAX_N 10
int G[MAX_N][MAX_N];
int vis[MAX_N][MAX_N] = {0};
int dx[4] = {0, 0, -1, 1};
int dy[4] = {-1, 1, 0, 0};
struct Point {
    Point() {}
    Point(int x, int y, Point *father) : x(x), y(y), father(father) {}
    int x, y;
    Point *father;
};

void read() {
    for (int i = 0 ; i < 5 ; ++i) {
        for (int j = 0 ; j < 5 ; ++j) {
            scanf("%d", &G[i][j]);
        } 
    }
}
bool check(Point pt) {
    if (pt.x < 0 || pt.x >= 5 || pt.y < 0 || pt.y >= 5 || vis[pt.x][pt.y] || (G[pt.x][pt.y] == 1)) return false;
    return true;
}
void solve() {
    
    Point st(0, 0, NULL), last_pt;
    Point pt[MAX_N * MAX_N];
    int ind = 0;

    queue<Point> que;
    que.push(st);
    vis[st.x][st.y] = 1;
    
    while (!que.empty()) {
        pt[ind] = que.front();
        que.pop();
        Point *now = &pt[ind];
        last_pt = pt[ind];
        ++ind;
        for (int i = 0 ; i < 4 ; ++i) {
            int tx = now->x + dx[i];
            int ty = now->y + dy[i];
            if (!check(Point(tx, ty, NULL))) continue;
            pt[ind].x = tx;
            pt[ind].y = ty;
            pt[ind].father = now;
            vis[pt[ind].x][pt[ind].y] = 1;
            que.push(pt[ind]);
            ++ind;
        }
    }
    stack<Point *> myStack;
    Point *p = &last_pt;
    while (p->father != NULL) {
        myStack.push(p);
        p = p->father;
    }
    printf("(0, 0)\n");
    while (!myStack.empty()) {
        p = myStack.top();
        myStack.pop();
        printf("(%d, %d)\n", p->x, p->y);
    }
}
int main() {
    read();
    solve();
    return 0;
}

转载于:https://www.cnblogs.com/WArobot/p/7922424.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值