zoukankan      html  css  js  c++  java
  • POJ3984(迷宫问题)

    迷宫问题
    Time Limit: 1000MS   Memory Limit: 65536K
    Total Submissions: 15154   Accepted: 9030

    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)
    注意打印路径。
    #include <iostream>
    #include <string.h>
    using namespace std;
    const int MAXN=1000005;
    struct Node{
        int y,x,pre;
        Node(){}
        Node(int cy,int cx,int cpre)
        {
            y=cy;
            x=cx;
            pre=cpre;
        }
    }que[MAXN];
    int front,rear;
    int mz[5][5];
    int vis[5][5];
    int dy[4]={0,1,0,-1};
    int dx[4]={1,0,-1,0};
    void print(int id)
    {
        Node now=que[id];
        if(now.pre==-1)
        {
            cout<<"("<<now.y<<", "<<now.x<<")"<<endl;
            return ;
        }
        print(now.pre);
        cout<<"("<<now.y<<", "<<now.x<<")"<<endl;
    }
    void bfs()
    {
        memset(vis,0,sizeof(vis));
        front=rear=0;
        que[rear++]=Node(0,0,-1);
        vis[0][0]=1;
        while(front!=rear)
        {
            Node now=que[front++];
            if(now.y==4&&now.x==4)
            {
                print(front-1);
                return ;
            }
            for(int i=0;i<4;i++)
            {
                int ny=now.y+dy[i];
                int nx=now.x+dx[i];
                if(0<=ny&&ny<5&&0<=nx&&nx<5&&!vis[ny][nx]&&mz[ny][nx]==0)
                {
                    que[rear++]=Node(ny,nx,front-1);
                    vis[ny][nx]=1;
                }
            }
        }
        
    }
    int main()
    {
        for(int i=0;i<5;i++)
            for(int j=0;j<5;j++)
                cin>>mz[i][j];
        bfs();
        return 0;
    }
  • 相关阅读:
    c++参考书籍
    安装驱动踩坑
    杂项讨论
    《机器学习篇》目录
    《计算机技术》目录
    数学:统计:参数估计
    神经网络
    数学:统计:数据的概括性度量
    数学:概率:一维随机变量
    多维随机变量:相互独立的随机变量
  • 原文地址:https://www.cnblogs.com/program-ccc/p/5668233.html
Copyright © 2011-2022 走看看