zoukankan      html  css  js  c++  java
  • POJ 3984

    题目链接:http://poj.org/problem?id=3984

    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)

    题解:

    裸的BFS水题。

    AC代码:

    #include<cstdio>
    #include<cstring>
    #include<queue>
    #include<stack>
    using namespace std;
    const int dx[4]={0,1,0,-1};
    const int dy[4]={1,0,-1,0};
    
    int mp[5][5];
    struct Node{
        int x,y;
        int cnt;
        Node(){}
        Node(int _x,int _y,int _cnt) {
            x=_x, y=_y, cnt=_cnt;
        }
        inline bool out() {
            return x<0 || x>=5 || y<0 || y>=5;
        }
    };
    queue<Node> Q;
    bool vis[5][5];
    Node pre[5][5];
    stack<Node> ans;
    
    int main()
    {
        memset(mp,1,sizeof(mp));
        for(int i=0;i<5;i++) for(int j=0;j<5;j++) scanf("%d",&mp[i][j]);
    
        memset(vis,0,sizeof(vis));
        Q.push((Node){0,0,0});
        vis[0][0]=1;
        while(!Q.empty())
        {
            Node now=Q.front(); Q.pop();
            if(now.x==4 && now.y==4)
            {
                ans.push(now);
                break;
            }
            for(int k=0;k<4;k++)
            {
                Node nxt=Node(now.x+dx[k],now.y+dy[k],now.cnt+1);
                if(nxt.out()) continue;
                if(mp[nxt.x][nxt.y]) continue;
                if(vis[nxt.x][nxt.y]) continue;
                Q.push(nxt);
                vis[nxt.x][nxt.y]=1;
                pre[nxt.x][nxt.y]=now;
            }
        }
    
        while(ans.top().cnt) ans.push(pre[ans.top().x][ans.top().y]);
        while(!ans.empty())
        {
            printf("(%d, %d)
    ",ans.top().x,ans.top().y);
            ans.pop();
        }
    }
  • 相关阅读:
    MySql数据库水平扩展过程
    (转)MySQL数据库水平切分的实现原理解析
    SVN安装使用
    servlet基础
    数据库读写分离的性能分析
    java的可变长参数
    java消息服务
    static/final成员与多态
    商业软件与开源软件
    托管堆
  • 原文地址:https://www.cnblogs.com/dilthey/p/9883551.html
Copyright © 2011-2022 走看看