每换一次方向 ne.num=now.num+1;
http://139.224.237.251:23333/problem/3001
3 3 0 0 2 2
000
110
110
1
3 3 0 0 2 2
001
101
100
2
#include<bits/stdc++.h>
using namespace std;
const int maxn=5005;
const int INF=0x3f3f3f3f;
int sx,sy,ex,ey,n,m,f,ans=INF;
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
char c[maxn][maxn];
int vis[maxn][maxn];
struct node{
int x;
int y;
int num;
};
bool check(int x,int y){
if(x>=1 && y>=1 && x<=n && y<=m && c[x][y]!='1')
return true;
return false;
}
void bfs(){
if(sx==ex && sy==ey){
f=1;
ans=0;
return;
}
queue<node> q;
node now,ne;
now.x=sx;
now.y=sy;
now.num=-1;
vis[now.x][now.y]=1;
q.push(now);
while(!q.empty()){
now=q.front();
q.pop();
ne.num=now.num+1;//换方向 开始-1->0不是换方向
for(int i=0;i<4;i++){
ne.x=now.x+dx[i];
ne.y=now.y+dy[i];
while(check(ne.x,ne.y)){
if(vis[ne.x][ne.y]==0){
vis[ne.x][ne.y]=1;
q.push(ne);
if(ne.x==ex && ne.y==ey){
f=1;
ans=min(ans,ne.num);
return;
}
}
ne.x+=dx[i];
ne.y+=dy[i];
}
}
}
}
int main()
{
cin>>n>>m>>sx>>sy>>ex>>ey;
sx++;sy++;ex++;ey++;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin>>c[i][j];
}
}
bfs();
if(f)
cout<<ans<<endl;
else
cout<<-1<<endl;
return 0;
}