zoukankan      html  css  js  c++  java
  • POJ 3984 迷宫问题(简单bfs+路径打印)

    传送门:

    http://poj.org/problem?id=3984

    迷宫问题
    Time Limit: 1000MS   Memory Limit: 65536K
    Total Submissions: 33105   Accepted: 18884

    Description

    定义一个二维数组:

    int maze[5][5] = {
    0, 1, 0, 0, 0,
    0, 1, 0, 1, 0,
    0, 0, 0, 0, 0,
    0, 1, 1, 1, 0,
    0, 0, 0, 1, 0,
    };

    它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。

    Input

    一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。

    Output

    左上角到右下角的最短路径,格式如样例所示。

    Sample Input

    0 1 0 0 0
    0 1 0 1 0
    0 0 0 0 0
    0 1 1 1 0
    0 0 0 1 0

    Sample Output

    (0, 0)
    (1, 0)
    (2, 0)
    (2, 1)
    (2, 2)
    (2, 3)
    (2, 4)
    (3, 4)
    (4, 4)

    Source

     

    分析:

    虽然bfs写得多一点,但路径打印的这还是第1个!!!

    利用栈的特性打印出来就好

    code:

    #include <stdio.h>
    #include <iostream>
    #include <stdlib.h>
    #include <algorithm>
    #include <string.h>
    #include<queue>
    #include<stack>
    using namespace std;
    int G[10][10];
    int dir[4][2]={1,0,0,1,-1,0,0,-1};
    int vis[10][10];
    struct node
    {
        int x,y;
    }pre[10][10];
    
    void pri()
    {
        stack<node> s;
        node p;
        p.x=4,p.y=4;
    
        while(1)
        {
            s.push(p);
            if(p.x==0&&p.y==0)
                break;
            p=pre[p.x][p.y];
        }
        int x,y;
        while(!s.empty())
        {
            x=s.top().x;
            y=s.top().y;
            printf("(%d, %d)
    ",x,y);
            s.pop();
        }
    }
    void bfs(int x,int y)
    {
        queue<node> q;
        node p,next;
    
        p.x=x,p.y=y;
        q.push(p);
        vis[x][y]=1;
    
        while(!q.empty())
        {
            p=q.front();
            q.pop();
    
            if(p.x==4&&p.y==4)
            {
                pri();
                return ;
            }
            for(int i=0;i<4;i++)
            {
                next.x=p.x+dir[i][0];
                next.y=p.y+dir[i][1];
    
                if(next.x>=0&&next.x<5&&next.y>=0&&next.y<5&&vis[next.x][next.y]==0&&G[next.x][next.y]==0)
                {
                    pre[next.x][next.y]=p;
                    vis[next.x][next.y]=1;
                    q.push(next);
                }
            }
        }
    }
    int main()
    {
        memset(G,0,sizeof(G));
        for(int i=0;i<5;i++)
        {
            for(int j=0;j<5;j++)
            {
                cin>>G[i][j];
            }
        }
        memset(vis,0,sizeof(vis));
        memset(pre,0,sizeof(pre));
        bfs(0,0);
        return 0;
    }
  • 相关阅读:
    python读取文件的方法
    python中global 和 nonlocal 的作用域
    android环境安装及配置
    python学习——sys.argv
    python学习——urlparse模块
    android:cmd下面用adb打log
    获取系统的换行符
    python----字符串方法
    类的继承---多重继承(两个父类有相同方法名和参数)
    Djngo 请求的生命周期
  • 原文地址:https://www.cnblogs.com/yinbiao/p/9400551.html
Copyright © 2011-2022 走看看