码迷,mamicode.com
首页 > 其他好文 > 详细

poj 3984 迷宫问题(bfs)

时间:2015-01-02 17:37:38      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:poj 3984 迷宫问题   dfs   递归打印路径   

                                                               迷宫问题
Time Limit: 1000MS
Memory Limit: 65536K
Total Submissions: 8695
Accepted: 5125

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)

Source


题解:

每个节点记录父节点,递归打印路劲。

CODE:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<algorithm>
#include<cstdlib>
#include<set>
#include<queue>
#include<stack>
#include<vector>
#include<map>

#define N 100010
#define Mod 10000007
#define lson l,mid,idx<<1
#define rson mid+1,r,idx<<1|1
#define lc idx<<1
#define rc idx<<1|1
const double EPS = 1e-11;
const double PI = acos(-1.0);
typedef long long ll;

const int INF=1000010;

using namespace std;

int mp[10][10];
int x[4]= {-1,0,1,0};
int y[4]= {0,1,0,-1};

struct node
{
    int x,y;
    int nextx,nexty;
    int op;
} a[1000];

queue<node>que;

void print(int x)
{
    if(a[x].op!=-1)
    {
        print(a[x].op);
        printf("(%d, %d)\n",a[x].x,a[x].y);
    }
}

void bfs()
{
    int first=0,num=0;
    node s,t;
    a[first].x=0,a[first].y=0;
    a[first].op=-1;
    que.push(a[first++]);
    while(que.size())
    {
        t=que.front();
        que.pop();
        if(t.x==4&&t.y==4)
        {
            print(num);
            break;
        }
        for(int i=0; i<4; i++)
        {
            a[first].x=t.x+x[i];
            a[first].y=t.y+y[i];
            if(a[first].x>=0&&a[first].x<=4&&a[first].y>=0&&a[first].y<=4&&mp[a[first].x][a[first].y]==0)
            {
                a[first].nextx=t.x;
                a[first].nexty=t.y;
                a[first].op=num;
                mp[a[first].x][a[first].y]=1;
                que.push(a[first++]);
            }
        }
        num++;
    }
}


int main()
{
    freopen("test.in","r",stdin);
    while(cin>>mp[0][0]>>mp[0][1]>>mp[0][2]>>mp[0][3]>>mp[0][4])
    {
        for(int i=1; i<5; i++)
            for(int j=0; j<5; j++)
                cin>>mp[i][j];
        printf("(0, 0)\n");
        bfs();
    }
    return 0;
}



poj 3984 迷宫问题(bfs)

标签:poj 3984 迷宫问题   dfs   递归打印路径   

原文地址:http://blog.csdn.net/acm_baihuzi/article/details/42341873

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!