版权声明:本文为博主原创文章,欢迎转载。如有问题,欢迎指正。 https://blog.csdn.net/weixin_42172261/article/details/88706421
题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=5748
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
struct node{
int x, y, d;
};
vector<int> a[100010], vis[100010];
int sx, sy, ex, ey, n, m;
int nextx[4]={0,0,1,-1};
int nexty[4]={1,-1,0,0};
int check(int x, int y)
{
if (x>0 && x<=n && y>0 && y<=m && vis[x][y]==0)
return 1;
return 0;
}
int bfs()
{
queue<node> que;
vis[sx][sy] = 1;
node start;
start.d=0;
start.x=sx;
start.y=sy;
que.push(start);
while(que.size())
{
start=que.front();
que.pop();
int x=start.x,y=start.y;
int state=a[x][y];
if(start.d%2)
{
if(state)
state=0;
else
state=1;
}
if (state == 0)
{
node t;
for(int i=2;i<4;i++)
{
t.x=x+nextx[i];
t.y=y+nexty[i];
t.d=start.d+1;
if(t.x== ex&& t.y==ey)
return t.d;
if(check(t.x,t.y))
{
vis[t.x][t.y] = 1;
que.push(t);
}
}
}
else
{
node t;
for(int i=0;i<2;i++)
{
t.x=x+nextx[i];
t.y=y+nexty[i];
t.d=start.d+1;
if(t.x== ex&& t.y==ey)
return t.d;
if(check(t.x,t.y))
{
vis[t.x][t.y] = 1;
que.push(t);
}
}
}
}
return -1;
}
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
scanf("%d%d", &n, &m);
for(int i=1;i<=n;i++){
a[i].clear();
vis[i].clear();
a[i].push_back(0);
vis[i].push_back(0);
}
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
{
int x;
cin>>x;
a[i].push_back(x);
vis[i].push_back(0);
}
scanf("%d%d%d%d", &sx, &sy, &ex, &ey);
if(sx==ex&&sy==ey)
printf("0\n");
else
printf("%d\n", bfs());
}
return 0;
}