• POJ 3984 迷宫问题


    迷宫问题
    Time Limit: 1000MS   Memory Limit: 65536K
    Total Submissions: 11501   Accepted: 6870

    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的水题,适合初学数据结构的做一做。

    /*************************************************************************
    	> File Name: 迷宫问题.cpp
    	> Author: Zhanghaoran0
    	> Mail: chiluamnxi@gmail.com
    	> Created Time: 2015年08月17日 星期一 16时23分14秒
     ************************************************************************/
    
    #include <iostream>
    #include <algorithm>
    #include <cstdio>
    #include <cstring>
    
    using namespace std;
    
    int map[6][6];
    int sx, sy, ex, ey;
    int dx[4] = {1, -1, 0, 0};
    int dy[4] = {0, 0 ,-1, 1};
    struct node{
        int x;
        int y;
        int lastn;
    }q[1000001];
    
    bool flag[6][6];
    
    void print(int x){
        if(q[x].lastn != -1){
            print(q[x].lastn);
        }
        printf("(%d, %d)
    ", q[x].x, q[x].y);
    }
    
    void bfs(){
        memset(flag, 0, sizeof(flag));
        int head = 0;
        int tail = 1;
        q[head].x = sx;
        q[head].y = sy;
        q[head].lastn = -1;
        while(head < tail){
            for(int i = 0; i < 4; i ++){
                int tempx = q[head].x + dx[i];
                int tempy = q[head].y + dy[i];
                if(flag[tempx][tempy] || tempx < 0 || tempx >= 5 || tempy < 0 || tempy >= 5 || map[tempx][tempy] == 1)
                    continue;
                q[tail].x = tempx;
                q[tail].y = tempy;
                q[tail].lastn = head;
                flag[tempx][tempy] = true;
                if(tempx == ex && tempy == ey){
                    print(tail);
                }
                tail ++;
            }
            head ++;
        }
    }
    
    int main(void){
        for(int i = 0; i < 5; i ++){
            for(int j = 0; j < 5; j ++){
                cin >> map[i][j];
            }
        }
    
        sx = 0;
        sy = 0;
        ex = 4;
        ey = 4;
    
        bfs();
        return 0;
    }


  • 相关阅读:
    ibatis插入正确但查询不出数据的问题
    Java 动态代理机制分析及扩展--转
    java实现插入排序算法 附单元测试源码
    unix基础知识
    作为大数据和云计算学习的一个序吧
    Understanding JVM Internals---不得不转载呀
    回文推理
    java 正则表达式提取html纯文本
    OpenCV功能界面和示例
    【POJ3268】Silver Cow Party 最短
  • 原文地址:https://www.cnblogs.com/chilumanxi/p/5136090.html
Copyright © 2020-2023  润新知