poj-3984-迷宫问题

来源:互联网 发布:linux 查看目录树结构 编辑:程序博客网 时间:2024/06/11 00:58

原文链接 :poj-3984-迷宫问题

原题:
迷宫问题
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 25699 Accepted: 14956
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)

问题分析:对于迷宫问题,可以用dfs也可以用bfs,该题所求的是路径最短的解,所以采用bfs

AC代码:

//poj3984 迷宫问题 bfs #include<cstdio>#include<queue>using namespace std;const int maxn=5;const int dirsize=4;const int startx=1;const int starty=1;const int endx=maxn;const int endy=maxn;struct dirnode//方向的结构体 {    int dirx,diry;}dir[dirsize]={{0,1},{1,0},{0,-1},{-1,0}};       struct node {    int x,y;};int arr[maxn+2][maxn+2];node father[maxn+2][maxn+2];//存放父节点,用于输出 queue<node>q;void coutresult(){    node path[maxn*maxn];    int count=0;    path[count].x=endx;    path[count].y=endy;    while(true)    {        if(path[count].x==startx&&path[count].y==starty)            break;        path[count+1]=father[path[count].x][path[count].y];        count++;    }    while(count>=0)    {        printf("(%d, %d)",path[count].x-1,path[count].y-1);        if(count>0)             printf("\n");        count--;    }}void bfs(){    int i;    node start;//    start.x=startx;start.y=starty;    q.push(start);    while(!q.empty())//队列不为空就一直搜索     {        node front;        front=q.front();q.pop();        if(front.x==endx&&front.y==endy)        {            coutresult();            return;        }        for(i=0;i<dirsize;i++)        {            int nextx=front.x+dir[i].dirx;            int nexty=front.y+dir[i].diry;            if(arr[nextx][nexty]==0)            {                father[nextx][nexty]=front;                node v;                v.x=nextx;                v.y=nexty;                q.push(v);            }        }        arr[front.x][front.y]=1;    }}int main(){    int i,j;    for(i=0;i<maxn+2;i++)//设置边界     {        arr[i][0]=1;        arr[maxn+1][i]=1;        arr[0][i]=1;        arr[i][maxn+1]=1;    }    for(i=1;i<=maxn;i++)        for(j=1;j<=maxn;j++)            scanf("%d",&arr[i][j]);    bfs();    return 0;}
原创粉丝点击