迷宫问题 POJ - 3984

14 篇文章 0 订阅
8 篇文章 0 订阅

简单的BFS搜索 + 回溯路径

目前形成的模式就是通过指针的方式回溯,暂未想到其他更好的方式

//leehaoze
#include <iostream>
#include <deque>
#include <string>
#include <vector>
#include <queue>
#include <cstdio>
#include <stack>
#include <algorithm>
#include <cstring>
#include <cctype>
#include <cstdio>
#include <cmath>
#include <cstdlib>

using namespace std;
const int INF = 1<<29;
#define INC_SAT( val ) (val = ((val)+1 > (val)) ? (val)+1 : (val))
#define ARR_SIZE( a ) ( sizeof( (a) ) / sizeof( (a[0]) ) )
#define ULL unsigned long long

#define MAXN 5

struct Point{
    Point():x_(0),y_(0),pre_(NULL){}
    Point(int x,int y,Point *p = NULL):x_(x),y_(y),pre_(p){}
    int x_;
    int y_;
    Point *pre_;
};

ostream &operator<<(ostream &out,Point &P){
    cout << '(' << P.x_ << ", " << P.y_ << ')' << endl;
    return out;
}

int Move_X[] = {0, 0, 1,-1};
int Move_Y[] = {1,-1, 0, 0};

int map[MAXN][MAXN];
bool visit[MAXN][MAXN];

void Input(){
    for (int i = 0; i < MAXN; ++i) {
        for (int j = 0; j < MAXN; ++j) {
            scanf("%d",&map[i][j]);
            visit[i][j] = false;
        }
    }
}

bool Legal(int dx,int dy){
    return dx >= 0 && dx < MAXN && dy >= 0 && dy < MAXN && !visit[dx][dy] && map[dx][dy] == 0;
}

void Back_Trace(Point *now){
    stack<Point> S;
    while(now != NULL){
        S.push(*now);
        now = now->pre_;
    }
    while(!S.empty()){
        cout << S.top();
        S.pop();
    }
}

void BFS(){
    queue<Point *> Q;
    Q.push(new Point(0,0));
    visit[0][0] = true;
    while(!Q.empty()){
        Point *now = Q.front();
        Q.pop();
        if(now->x_ == 4 && now->y_ == 4){
            Back_Trace(now);
        }
        for (int i = 0; i < 4; ++i) {
            int dx = now->x_ + Move_X[i];
            int dy = now->y_ + Move_Y[i];
            if(Legal(dx,dy)){
                visit[dx][dy] = true;
                Q.push(new Point(dx,dy,now));
            }
        }

    }
}

int main() {
#ifdef LOCAL
    freopen("IN.txt", "r", stdin);
#endif
    std::ios::sync_with_stdio(false);
    Input();
    BFS();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值