zoukankan      html  css  js  c++  java
  • POJ.3894 迷宫问题 (BFS+记录路径)

    POJ.3894 迷宫问题 (BFS+记录路径)

    题意分析

    定义一个二维数组:

    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表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。

    一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。

    简单的BFS,路径记录开一个二维数组就好。

    代码总览

    #include <cstdio>
    #include <algorithm>
    #include <cstring>
    #include <queue>
    #include <vector>
    #define nmax 6
    using namespace std;
    int mp[nmax][nmax];
    typedef struct{
        int x;
        int y;
        bool isvis;
    }mes;
    typedef struct{
        int x;
        int y;
    }point;
    mes visit[nmax][nmax];
    int spx[5] = {0,1,0,-1};
    int spy[5] = {1,0,-1,0};
    bool check(point temp)
    {
        if(temp.x <0 || temp.x >=5 ||temp.y < 0 || temp.y >=5 || visit[temp.x][temp.y].isvis|| mp[temp.x][temp.y] == 1)
            return false;
        else return true;
    }
    void bfs()
    {
        memset(visit,0,sizeof(visit));
        queue<point> q;
        while(!q.empty()) q.pop();
        point temp = {0,0},head;
        visit[temp.x][temp.y].isvis = true;
        q.push(temp);
        while(!q.empty()){
            head = q.front(); q.pop();
            if(head.x == 4 && head.y == 4){
                return;
            }
            for(int i = 0;i<4;++i){
                temp.x = head.x + spx[i];
                temp.y = head.y + spy[i];
                if(check(temp)){
                    visit[temp.x][temp.y].isvis = true;
                    visit[temp.x][temp.y].x = head.x;
                    visit[temp.x][temp.y].y = head.y;
                    q.push(temp);
                }
            }
        }
    }
    void output(point temp)
    {
        point h;
        vector<point> v; v.clear();
        while(1){
            v.push_back(temp);
            if(temp.x == 0 && temp.y == 0) break;
            h.x = visit[temp.x][temp.y].x;
            h.y = visit[temp.x][temp.y].y;
            temp = h;
        }
        for(int i = v.size()-1;i>=0;--i){
            printf("(%d, %d)
    ",v[i].x,v[i].y);
        }
    }
    int main()
    {
        for(int i = 0;i<5;++i){
            for(int j = 0;j<5;++j){
                scanf("%d",&mp[i][j]);
            }
        }
        bfs();
        output({4,4});
        return 0;
    }
    
  • 相关阅读:
    JDK 14的新特性:更加好用的NullPointerExceptions
    技术回顾系列:最新最热门的技术大事-第一周
    JDK 14的新特性:instanceof模式匹配
    JDK 15 JAVA 15的新特性展望
    怎么break java8 stream的foreach
    java 8 stream中的Spliterator简介
    怎么在java中创建一个自定义的collector
    java 8 stream reduce详解和误区
    java stream中Collectors的用法
    java关于throw Exception的一个小秘密
  • 原文地址:https://www.cnblogs.com/pengwill/p/7367051.html
Copyright © 2011-2022 走看看