您的位置:首页 > 其它

迷宫问题 POJ - 3984

2017-03-22 20:46 183 查看
简单的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();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  poj bfs