poj3984迷宫问题

来源:互联网 发布:网络综合布线品牌 编辑:程序博客网 时间:2024/06/06 01:39

http://poj.org/problem?id=3984

宽搜,但是最后要求输出路径。

所以队列里的元素应记录了指向父结点。我在node结构体里设置了father成员,然而它并不是直接指向父结点的指针,而是存储父结点在队列中的位置。

这样的话,最后输出路径的时候,通过father(父结点队列位置)就可以访问父结点了。大笑

#include <stdio.h>#include <string.h>typedef struct node{    int x,y,dis,father;}node;node queue[10000];int maze[5][5],visited[5][5];int dir[4][2]={{0,-1},{-1,0},{0,1},{1,0}};//左上右下void init(){    int i,j;    for(i=0;i<5;i++)        for(j=0;j<5;j++)            scanf("%d",&maze[i][j]);    memset(visited,0,sizeof(visited));}void Output(node s){    if(s.father==-1)        return;    else        Output(queue[s.father]);    printf("(%d, %d)\n",s.x,s.y);}void Breadth_FirstSearch(){    int front,rear,i;    node start,head,temp;    front=rear=0;    start.x=start.y=0;    start.dis=1;    start.father=-1;    queue[rear++]=start;    while(front<rear)    {        head=queue[front++];//取队头        for(i=0;i<4;i++)        {            temp.x=head.x+dir[i][0];            temp.y=head.y+dir[i][1];            temp.dis=head.dis+1;            if(temp.x>=0&&temp.x<5&&temp.y>=0&&temp.y<5&&maze[temp.x][temp.y]!=1&&visited[temp.x][temp.y]==0)            {                if(temp.x==4&&temp.y==4)                {                    printf("(0, 0)\n");                    Output(head);                    printf("(4, 4)\n");                    return;                }                visited[temp.x][temp.y]=1;                temp.father=front-1;//head在queue[]中的位置                queue[rear++]=temp;            }        }    }}int main(){    init();    Breadth_FirstSearch();    return 0;}

0 0
原创粉丝点击