李若谷 @ 2020-01-22 21:40:51
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <queue>
#include <cstring>
using namespace std;
const int N = 1500;
char a[N][N];
int n;
int sx,sy,ex,ey;
queue <pair<int,int> > start;
queue <pair<int,int> > final;
int steps[N][N];
int stepe[N][N];
const int dx[4] = {-1,1,0,0};
const int dy[4] = {0,0,-1,1};
int bfs()
{
start.push(make_pair(sx,sy));
final.push(make_pair(ex,ey));
steps[sx][sy] = 0;
stepe[ex][ey] = 0;
if(sx==ex&&sy==ey)
{
return 0;
}
while(!start.empty()||!final.empty())
{
int lens = start.size();
int lene = final.size();
// 正向
for(register int i=0;i<lens;i++)
{
int curx = start.front().first, cury = start.front().second;
start.pop();
for(register int j=0;j<4;j++)
{
int xx = curx+dx[j];
int yy = cury+dy[j];
if(a[xx][yy] == '0' &&xx<=n&&yy<=n&&xx>=1&&yy>=1&&steps[xx][yy]==-1)
{
if(stepe[xx][yy]!=-1)
{
return steps[curx][cury] + 1 + stepe[xx][yy]; //steps[curx][cury] + 1其实就是 steps[xx][yy]
}
steps[xx][yy] = steps[curx][cury] + 1;
start.push(make_pair(xx,yy));
}
}
}
//反向
for(register int i= 0;i<lene;i++)
{
int curx = final.front().first, cury = final.front().second;
final.pop();
for(int j=0;j<4;j++)
{
int xx = curx + dx[j];
int yy = cury + dy[j];
if(a[xx][yy] == '0'&&xx<=n&&yy<=n&&xx>=1&&yy>=1&&stepe[xx][yy] == -1)
{
if(steps[xx][yy]!=-1)
{
return steps[xx][yy] + stepe[curx][cury] + 1;
}
stepe[xx][yy] = stepe[curx][cury] + 1;
final.push(make_pair(xx,yy));
}
}
}
}
}
int main()
{
memset(steps,-1,sizeof(steps));
memset(stepe,-1,sizeof(stepe));
scanf("%d",&n);
for(register int i=1;i<=n;i++)
{
scanf("%s",&a[i]);
}
scanf("%d%d%d%d",&sx,&sy,&ex,&ey);
printf("%d\n",bfs());
return 0;
}