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)\n",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;
}
posted @ 2017-07-29 10:32  pengwill  阅读(133)  评论(0编辑  收藏  举报