#include<bits/stdc++.h>
using namespace std;
int dx[4]={0,1,-1,0};
int dy[4]={1,0,0,-1};
int r,cc;
char c[2005][2005];
int vit[2005][2005];
struct node{
int x;//行
int y;//列
int step;//步数
}a[2005];
void bfs(){
int h=1,t=1;//h头t尾
while(h<=t){
for(int i=0;i<=3;i++){
int xx=a[h].x+dx[i];
int yy=a[h].y+dy[i];
if(c[xx][yy]=='.'&&vit[xx][yy]==0&&xx>0&&xx<=r&&yy>0&&yy<=cc){
//cout<<xx<<" "<<yy<<" "<<a[h].x<<" "<<a[h].y<<endl;
vit[xx][yy]=1;
t++;
a[t].x=xx;
a[t].y=yy;
a[t].step=a[h].step+1;
if(a[t].x==r&&a[t].y==cc){
cout<<a[t].step<<endl;
return;
}
}
}
h++;
}
}
int main(){
cin>>r>>cc;
for(int i=1;i<=r;i++){
for(int j=1;j<=cc;j++){
cin>>c[i][j];
}
}
a[1].x=a[1].y=a[1].step=1;
vit[1][1]=1;
bfs();
return 0;
}
看了源代码 我是一片懵,因为这次的代码用到了结构体 struct 他可以把变量撞到一个数组里面,在调用时数组的一项可以有多项数据,十分 nice.
struct node{
int x;//行
int y;//列
int step;//步数
}a[2005];
再用上宽搜 bfs,他就是把数依次存入队列中遍历,无需回溯,速度飞快,而头超过尾时便遍历结束输出。