#include <bits/stdc++.h>
using namespace std;
const int N =1001;
char map1[N][N];
int visted[N][N];
int dirs[4][4] = {{-1,0},{1,0},{0,-1},{0,1}};
int n,m,xs,ys,xt,yt;
struct point{
int x;
int y;
int step;
};
queue<point> que;
int main(int argc , char * argv[]){
// freopen("/newhome/wangjd/leetcode/testin.txt","r",stdin);
cin>>n>>m>>xs>>ys>>xt>>yt;
for(int i = 1 ; i <=n ; ++i){
for(int j = 1 ;j<=m; ++j){
cin>>map1[i][j];
}
}
point p;
p.x=xs;
p.y=ys;
p.step=0;
que.push(p);
visted[xs][ys]=1;
int flag = 0 ;
while(!que.empty()){
point temp = que.front();
que.pop();
if(temp.x==xt && temp.y == yt ){
flag = 1;
cout<<temp.step<<endl;
break;
}
for(int i = 0 ; i <4;++i){
int next_x = temp.x + dirs[i][0];
int next_y = temp.y + dirs[i][1];
if(next_x>=1 && next_x<= n && next_y >=1 && next_y<=m && map1[next_x][next_y]=='.'&& visted[next_x][next_y]==0){
point new_temp;
new_temp.x = next_x;
new_temp.y = next_y;
new_temp.step = temp.step+1;
que.push(new_temp);
visted[next_x][next_y]=1;
}
}
}
if(!flag){
cout<<-1<<endl;
}
}
bfs练习
最新推荐文章于 2024-07-22 09:38:37 发布