您的位置:首页 > 其它

poj 3984 迷宫问题..

2015-10-23 12:50 337 查看
广搜....一开始我用STL 队列进行广搜 , 却发现怎么也不会找路径,仔细想想,广搜安曾遍历, 每一层的 step 都是一样的,所以无法找到路径,然后百度了下别人的代码,看到用了模拟队列写,用一个pre记录这个节点的前一个节点在哪,然后递归输出结果,自己仔细想想吧

# include<cstdio>
# include<cstdlib>
# include<algorithm>
# include<queue>
# include<string.h>

using namespace std;

int map[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}
};
int front=0,rear=1;
int fx[4][2]={0,1,0,-1,1,0,-1,0};
struct node{
int x,y,pre;
}que[100];

void print(int i){ //递归打印路径....

if(que[i].pre!=-1){
print(que[i].pre);
printf("(%d, %d)\n",que[i].x,que[i].y);
}

}

void bfs(int a,int b){
int xx,yy;
que[front].x=a;
que[front].y=b;
que[front].pre=-1;
while(front<rear){

for(int i=0;i<4;i++){
xx=que[front].x+fx[i][0]; //这块不知道直接que[rear].x 咋错了
yy=que[front].y+fx[i][1];
if(xx >=0 && xx<5 &&yy>=0 &&yy<5 && map[xx][yy]==0 ){
if(xx==4 && yy==4) print(front);
que[rear].x=xx;
que[rear].y=yy;
map[que[rear].x][que[rear].y]=1;
que[rear].pre=front;
rear++;

}

}
front++;
}

}

int main(){
printf("(0, 0)\n");
bfs(0,0);
printf("(4, 4)\n");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: