POJ 3984 迷宫问题 (BFS + Stack)

/*************************************************************************
	> 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;
}
posted @ 2017-11-29 19:57  ojnQ  阅读(175)  评论(0编辑  收藏  举报