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

    K - 迷宫问题
    Time Limit:1000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u

    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 <cstdio>
    #include <cstring>
    #include <queue>
    #include <cstdlib>
    #include <cmath>
    #include <cctype>
    #define N 110
    using namespace std;
    
    bool maps[6][6];//由于地图读入只有0, 1所以用bool类型就可以
    int dir[4][2] = {0,1, 1,0, 0,-1, -1,0};//方向
    
    struct node
    {
        int x, y;
    }q1, m[5][5];//x, y为之前点的坐标
    
    void Put(node q)//递归输出路径
    {
        if(q.x == 0 && q.y == 0) {
            printf("(0, 0)
    ");
            return;
        }
        else Put(m[q.x][q.y]);
        printf("(%d, %d)
    ", q.x, q.y);
    }
    
    void BFS()
    {
        q1 = {0, 0};
        queue<node>q;
        q.push(q1);
        maps[0][0] = true;
    
        while(!q.empty()) {
            node q2;
            q2 = q.front();
            q.pop();
            if(q2.x == 4 && q2.y == 4) {
                Put(q2);//输出路径
            }
            for(int i = 0; i < 4; i++) {
                int x, y;
                x = q2.x + dir[i][1];
                y = q2.y + dir[i][0];
                if(!maps[x][y] && x >= 0 && x < 5 && y >= 0 && y < 5) {
                    maps[x][y] = true;//
                    m[x][y] = {q2.x, q2.y};
                    q1 = {x, y};
                    q.push(q1);
                }
            }
        }
    }
    
    int main()
    {
        for(int i = 0; i < 5; i++)
        for(int j = 0; j < 5; j++) {
            scanf("%d", &maps[i][j]);
        }
        BFS();//对地图广搜
    
        return 0;
    }



  • 相关阅读:
    Rsync常见运维操作命令
    [图文详解] Sublime Text在Windows/Ubuntu/Mac OSX中配置使用CTags
    Sublime Text : 创建工程
    Sublime Text 插件 & 使用技巧
    如何解决adb devices 端口被占用的问题zz
    Nginx 服务器安装及配置文件详解
    把notepad++设置为系统全局文本默认打开应用
    Ubuntu 下载 & 编译 Android5.1 源码
    同步、更新、下载Android Source & SDK from 国内镜像站
    如何为Linux生成和打上patch
  • 原文地址:https://www.cnblogs.com/wangyuhao/p/4688087.html
Copyright © 2011-2022 走看看