POJ 3984 迷宫问题【BFS/路径记录/手写队列】

迷宫问题
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 31428 Accepted: 18000
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<string>
#include<cstdlib>
#include<cmath>
#include<iostream>
#include<cstring>
#include<set>
#include<queue>
#include<algorithm>
#include<vector>
#include<map>
#include<cctype>
#include<stack>
#include<sstream>
#include<list>
#include<assert.h>
#include<bitset>
#include<numeric>
#define debug() puts("++++")
#define gcd(a,b) __gcd(a,b)
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define fi first
#define se second
#define pb push_back
#define sqr(x) ((x)*(x))
#define ms(a,b) memset(a,b,sizeof(a))
#define sz size()
#define be begin()
#define pu push_up
#define pd push_down
#define cl clear()
#define lowbit(x) -x&x
#define all 1,n,1
#define rep(i,n,x) for(int i=(x); i<(n); i++)
#define in freopen("in.in","r",stdin)
#define out freopen("out.out","w",stdout)
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> P;
const int INF = 0x3f3f3f3f;
const LL LNF = 1e18;
const int maxn = 1e6;
const int maxm = 10;
const double PI = acos(-1.0);
const double eps = 1e-8;
//const int dx[] = {-1,1,0,0,1,1,-1,-1};
//const int dy[] = {0,0,1,-1,1,-1,1,-1};
const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

int a[5][5];
int dx[4]={1,-1,0,0};
int dy[4]={0,0,-1,1};
int front=0,rear=1;
struct node
{
    int x,y,pre;
}q[100];

void print(int i)
{
    if(q[i].pre!=-1)
    {
        print(q[i].pre);
        cout<<"("<<q[i].x<<", "<<q[i].y<<")"<<endl;
    }
}

void bfs(int x1,int y1)
{
    q[front].x=x1;
    q[front].y=y1;
    q[front].pre=-1;
    while(front < rear)
    {
        for(int i=0; i<4; i++)
        {
            int nx = dx[i] + q[front].x;
            int ny = dy[i] + q[front].y;
            if(nx<0||nx>=5||ny<0||ny>=5||a[nx][ny])
                continue;
            else
            {
                a[nx][ny]=1;
                q[rear].x=nx;
                q[rear].y=ny;
                q[rear].pre=front;
                rear++;
            }
            if(nx==4&&ny==4) print(front);
        }
        front++;
    }
}

int main()
{
    for(int i=0;i<5;i++)
        for(int j=0;j<5;j++)
        scanf("%d",&a[i][j]);
    cout<<"(0, 0)"<<endl;
    bfs(0,0);
    cout<<"(4, 4)"<<endl;
}

posted @ 2018-06-16 23:53  Roni_i  阅读(285)  评论(0编辑  收藏  举报