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

                                                          迷宫问题


    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<cstdio>
    #include<iostream>
    #include<algorithm>
    #include<queue>
    using namespace std;
    const int  inf=-1;
    typedef pair <int,int> TP;
    int a[5][5];
    int m=0,n=0;
    int d[5][5];
    int dx[4]= {1,0,-1,0},dy[4]= {0,1,0,-1};
    TP xxx[30];
    void bfs()
    {
        queue<TP> que;
        for(int i=0; i<n; i++)
            for(int j=0; j<m; j++)
                d[i][j]=inf;
        que.push(TP(0,0));
        d[0][0]=0;
        while(!que.empty())
        {
    
            TP p = que.front();
            que.pop();
            if(p.first==4&&p.second==4) break;
            for(int i=0; i<4; i++)
            {
                int nx=p.first+dx[i],ny=p.second+dy[i];
                if(0 <= nx && 0 <= ny && nx < n && ny < m && a[nx][ny]!=1&&d[nx][ny]==inf)
                {
                    que.push(TP(nx,ny));
                    d[nx][ny]=d[p.first][p.second]+1;
                }
            }
        }
    }
    
    int dfs(int x,int y)
    {
        if(x==0&&y==0) return 0;
        xxx[d[x][y]].first=x,xxx[d[x][y]].second=y;
        if(d[x-1][y]==d[x][y]-1) dfs(x-1,y);
        else if(d[x+1][y]==d[x][y]-1) dfs(x+1,y);
        else if(d[x][y-1]==d[x][y]-1) dfs(x,y-1);
        else if(d[x][y]==d[x][y+1]-1) dfs(x,y+1);
    }
    int main()
    {
        m=5,n=5;
        for(int i=0; i<5; i++)
            for(int j=0; j<5; j++)
                scanf("%d",&a[i][j]);
        bfs();
        dfs(4,4);
        for(int i=0;i<d[4][4]+1;i++)
            printf("(%d, %d)
    ",xxx[i].first,xxx[i].second);
        return 0;
    }
    



  • 相关阅读:
    rm
    Linux下解包/打包,压缩/解压命令
    虚拟机安装---vm12+ubuntukylin16.04
    mysql-5.6.41-winx64安装
    tensorflow学习笔记一------下载安装,配置环境(基于ubuntu16.04 pycharm)
    大一上学期C语言学习心得总结
    常见HTTP状态码
    Java语言基础及java核心
    linux下安装JMeter(小白教程)
    Linux下安装JDK(小白教程)
  • 原文地址:https://www.cnblogs.com/chinashenkai/p/9451421.html
Copyright © 2011-2022 走看看