POJ 3984 迷宫问题

来源:互联网 发布:校宝软件下载 编辑:程序博客网 时间:2024/06/05 18:33
迷宫问题
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 24627 Accepted: 14380

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 00 1 0 1 00 0 0 0 00 1 1 1 00 0 0 1 0

Sample Output

(0, 0)(1, 0)(2, 0)(2, 1)(2, 2)(2, 3)(2, 4)(3, 4)(4, 4)

可以说是搜索入门题了,5*5的矩阵,问你最短路径。

难点在于怎么输出最短路径的过程。

本来想bfs无非就是用一个队列,后来发现用stl的queue 的话好像没办法保存路径(或者很麻烦、不想去想)

还是老老实实用结构体数组吧,输出的时候要用递归的思路,好像现在慢慢熟练起来了(Recursion)

#include <iostream>#include <cstdio>#include <cstring>#include <cmath>#include <queue>#include <cctype>using namespace std;int M[10][10];bool visit[10][10];int dx[4] = {1,-1,0,0};int dy[4] = {0,0,1,-1};struct p{    int x,y;    int pre;};p q[500];//因为一个点只有一个pre并且可由下标唯一确定void print(int l){    if(q[l].pre==-1)    {        printf("(%d, %d)\n",q[l].x,q[l].y);        return ;    }    print(q[l].pre);    printf("(%d, %d)\n",q[l].x,q[l].y);//递归输出结果}void bfs(){    p now,next;    now.x=0,now.y=0,now.pre=-1;    //queue<p> q;    visit[0][0]=1;    int l=0,r=0;    q[r++]=now;    while(l<r)    {        now=q[l];        if(now.x==4&&now.y==4)        {            print(l);            return;        }        l++;        for(int i=0; i<4; i++)        {            next.x=now.x+dx[i];            next.y=now.y+dy[i];            if(next.x>=0&&next.x<5&&next.y>=0&&next.y<5&&visit[next.x][next.y]==0&&M[next.x][next.y]==0)            {                next.pre=l-1;                q[r++]=next;                visit[next.x][next.y]=1;            }        }    }}int main(){    for(int i=0; i<5; i++)        for(int j=0; j<5; j++)            cin>>M[i][j];    bfs();    return 0;}

原创粉丝点击