POJ 3984 迷宫问题

 
迷宫问题
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 36095   Accepted: 20424

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)

注意下输出格式,第一个数后的逗号和第二个数之间是有一个 空格 的,如果没有会报Presentation Error;

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

int maze[6][6];
int go[4][2] = {1,0,-1,0,0,-1,0,1};
bool mark[6][6];

//用的结构体数组表示,这样比用队列表示好还原走过的路
struct node
{
    int x,y;
    int route;
}path[30];
int cu,ne;

//学习一下bfs的这种写法
void bfs()
{
    cu = 0;
    ne = 1;
    path[0].x=0;
    path[0].y=0;
    path[0].route = -1;
    while(cu<ne)
    {
        for(int i=0;i<4;i++)
        {
            path[ne].x = path[cu].x + go[i][0];
            path[ne].y = path[cu].y + go[i][1];
            if(path[ne].x>=0&&path[ne].x<5&&path[ne].y>=0&&path[ne].y<5&&!mark[path[ne].x][path[ne].y]&&maze[path[ne].x][path[ne].y]!=1)
            {
                mark[path[ne].x][path[ne].y]=1;
                //记录 cu ,这样最后还原出来的路径就是最短的路径
                path[ne].route = cu;
                ne++;
                //走到尽头
                if(path[ne].x==4&&path[ne].y==4)
                    return;
            }
        }
        cu++;
    }
}

//通过函数不断地递归调用,实现把起点到末尾走过的最短路径输出来
void print(node now)
{
    //输出的时候','和第二个数之间有个空格,不然会有Presentation Error
    if(now.route == -1)
        printf("(%d, %d)\n",now.x,now.y);
    else
    {
        print(path[now.route]);
        printf("(%d, %d)\n",now.x,now.y);
    }
}

int main()
{
    for(int i=0;i<5;i++)
        for(int j=0;j<5;j++)
            scanf("%d",&maze[i][j]);
    memset(mark,0,sizeof(mark));
    bfs();
    //print的形参要传入走到末尾后的最新值,然后通过递归,递归到起点,然后在函数返回上一个函数的过程中
    //输出从起点到终点走过的最短路径。
    print(path[ne-1]);
    return 0;
}
Ac代码

 

 

posted @ 2018-11-27 15:42  HiCYP  阅读(121)  评论(0编辑  收藏  举报