例题:
代码:(好好看注释)
//BFS广搜解决迷宫问题
#include <iostream>
#include <algorithm>
#include <queue>
#include <string.h>
using namespace std;
typedef long long ll;
const int N=1024;
/*5 4
1 1 2 1
1 1 1 1
1 1 2 1
1 2 1 1
1 1 1 2
1 1 4 3案例 */
int dx[4]={0,0,1,-1};//四个方向
int dy[4]={1,-1,0,0};
int a[N][N],v[N][N];//a是原数组,v是访问数组
struct point{//为了存坐标和走了的步数,开一个结构体和队列
int x;
int y;
int step;
};
queue<point> r;//申请队列
int main()
{
//输入
int n,m;
scanf("%d %d",&n,&m);
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
scanf("%d",&a[i][j]);
}
}
int startx,starty,p,q;//起点坐标和终点坐标
scanf("%d %d %d %d",&startx,&starty,&p,&q);
//BFS
point start;
start.x=startx;
start.y=starty;
start.step=0;
r.push(start);//将起点入队
v[startx][starty]=1;//起点已经访问
int flag=0;
while(!r.empty()){//不要忘了括号 ,这是条件
int x=r.front().x;
int y=r.front().y;
if(x==p&&y==q){
flag=1;
printf("%d",r.front().step);
break;
}
for(int k=0;k<=3;k++){
int tx=x+dx[k];
int ty=y+dy[k];
if(a[tx][ty]==1&&v[tx][ty]==0){//坐标(tx,ty)是空地,即没有障碍物&&没有被访问
//入队
point temp;
temp.x=tx;
temp.y=ty;
temp.step=r.front().step+1;
r.push(temp);
v[tx][ty]=1;
}
}
r.pop();//拓展完了需要将队首元素出队
}
if(flag==0) printf("NO");
return 0;
}
运行结果