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

2万+

被折叠的 条评论
为什么被折叠?



