poj3984迷宫问题

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值