poj3984迷宫问题 入门搜索bfs

这道题如果不要求写路径,就是一道简单的bfs

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;

int map[5][5];
int dx[4]={1,-1,0,0},dy[4]={0,0,1,-1};

struct Node{                              //定义了一个结构体数组,用来模拟队列
    int x;
int y;
int pre;
}que[100];

int head=0,tot=1;                      //head表示每一步,tot表示有多少种尝试

void print(int s){                                  //这里采用了递归输出,        0.0表示学到了
    if(que[s].pre!=-1){                
print(que[s].pre);
printf("(%d, %d)\n",que[s].x,que[s].y);
}
}

void bfs(int x,int y){                            //bfs主体
    que[head].x=x;                              
que[head].y=y;
que[head].pre=-1;
while(head<tot){
int i,m,n;
for(i=0;i<4;i++)                                  //每次加入方向进行循环
     {
m=que[head].x+dx[i];
n=que[head].y+dy[i];
if(m>4||n>4||m<0||n<0||map[m][n]==1)                                  //如果到达边界,或者为墙,或者已经访问过就跳出 ,继续循环
       continue;
map[m][n]=1;                                                                      //将访问的节点设为已访问
         que[tot].x=m;                                                            //入队
que[tot].y=n;
que[tot].pre=head;
tot++;                                                                             //这里很重要
    if(m==4&&n==4)                                                        //如果找到终点,直接调用输出
         {
print(head);
}
}
head++;                                                                        //步数加一
}
}


int main(){
int i,j;
for(i=0;i<5;i++)
for(j=0;j<5;j++)
scanf("%d",&map[i][j]);
cout<<"(0, 0)"<<endl;
bfs(0,0);
cout<<"(4, 4)"<<endl;
return 0;
}

你可能感兴趣的:(poj,bfs,3984)