zoukankan      html  css  js  c++  java
  • poj 3984 迷宫问题

    题意:中文的,不解释了

    思路:唯一的难点是如何处理最短路径的输出,我的解决办法是将最短的路径储存在链表里,然后放到堆栈了保护起来+倒序一下

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <stack>
    using namespace std;
    struct Path
    {
    int x, y;
    Path *forward;
    Path() {x=0; y=0; forward=NULL;}
    }path;
    stack<Path> st;
    int mov[][2]={{1, 0}, {-1, 0}, {0, -1}, {0, 1}}, cnt=1000000;
    bool vis[5][5];
    int map[5][5];

    void dfs(Path p, int step)
    {
    if(p.x==4 && p.y==4)
    {
    if(step<cnt)
    {
    cnt=step;
    path=p;
    while(!st.empty()) st.pop();
    while(path.forward) {st.push(path); path=*path.forward;}
    }
    return;
    }

    for(int i=0; i<4; i++)
    {
    int xh=p.x+mov[i][0];
    int yh=p.y+mov[i][1];
    if(xh>=0 && xh<5 && yh>=0 && yh<5 && !vis[xh][yh] && !map[xh][yh])
    {
    Path ph;
    ph.x=xh;
    ph.y=yh;
    ph.forward=&p;
    vis[xh][yh]=1;
    dfs(ph, step+1);
    vis[xh][yh]=0;
    }
    }
    }

    int main()
    {
    for(int i=0; i<5; i++)
    for(int j=0; j<5; j++)
    scanf("%d", &map[i][j]);
    memset(vis, 0, sizeof(vis));
    dfs(path, 0);
    printf("(0, 0)\n");
    while(!st.empty())
    {
    path=st.top();
    st.pop();
    printf("(%d, %d)\n", path.x, path.y);
    }
    return 0;
    }
    作者:FreeAquar
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    应用 memcached 提升站点性能
    Servlet 工作原理解析
    AJAX的一些基础和AJAX的状态
    回调地狱以及用promise怎么解决回调地狱
    Ajax的封装
    promise的理解和应用
    jsonp跨域
    浅谈事件冒泡和事件捕获
    JS中的兼容问题总结
    JS写的二级导航栏(利用冒泡原理)
  • 原文地址:https://www.cnblogs.com/FreeAquar/p/2098018.html
Copyright © 2011-2022 走看看