• POJ 3984 迷宫问题 (BFS + Stack)



    **链接 : ** 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)
    ");
        while (!myStack.empty()) {
            p = myStack.top();
            myStack.pop();
            printf("(%d, %d)
    ", p->x, p->y);
        }
    }
    int main() {
        read();
        solve();
        return 0;
    }
    
  • 相关阅读:
    offsetLeft 和 style.left
    wampserver 使用小结,操作一:wamp 配置虚拟域名 操作二:wamp 127.0.0.1正常打开,localhost空白403/404
    多栏目显示隐藏
    javascript闭包,for循环同步和异步
    wordpress 主题模板常用内容调用代码
    ECMAScript 6 let和var区别和应用
    js jquery获取所有同级相邻元素,同tag标签,中间有间隔其他tag的不算,不是siblings
    微信小程序如何使用百度API实现身份证查询
    微信小程序视频弹幕效果
    不得不知的小程序基本知识
  • 原文地址:https://www.cnblogs.com/WArobot/p/7922424.html
Copyright © 2020-2023  润新知