代码改编自《啊哈!算法》
主要改了:
浪费空间的int数组
声明全局变量
加强了可读性(如bool)
增加了自己的理解的注释
#include<cstdio>
#include<iostream>
using namespace std;
typedef unsigned long long ll;
struct node{
int x,y,s;
}que[2501];
int head,tail;
int a[51][51];
bool book[51][51];
int next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
int n,m,startx,starty,p,q,tx,ty;
bool flag;
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
cin>>a[i][j];
cin>>startx>>starty>>p>>q;
head=1;
tail=1;
//记录第一个结点的坐标、步数
que[tail].x=startx;
que[tail].y=starty;
que[tail].s=0;
tail++;
book[startx][starty]=true;//标记出发点为已经访问
flag=false;
while(head<tail)//队列非空时候循环
{
for(int k=0;k<4;k++){
tx=que[head].x+next[k][0];
ty=que[head].y+next[k][1];
//判断越界
if(tx<1||tx>n||ty<1||ty>m)continue;
//判断是否为障碍物或者已经访问
if(a[tx][ty]==0&&book[tx][ty]==false)
{
book[tx][ty]=true;//结点标记为已经访问 (宽搜不需要还原(回溯
que[tail].x=tx;
que[tail].y=ty;
que[tail].s=que[head].s+1;//步数是父节点+1
tail++;
}
if(tx==p&&ty==q)
{
flag=true;//到达目的地,flag标记为 true
break;
}
}
if(flag==true)break;//如果搜到了就退出
head++;//展开
}
cout<<que[tail-1].s<<endl;//因为for中tail多加了个1,故在此-1
return 0;
}
该代码实现了一个宽度优先搜索(BFS)算法,用于在一个障碍物分布的二维网格中找到从起点到终点的最短路径。通过一个二维数组表示网格,全局变量已优化,使用bool类型增强可读性,并记录每个节点的步数。算法遍历网格,遇到未访问的相邻节点并更新步数,直到找到目标位置。
1157

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



