【题目】
【题意】
状态0上下移动一步,状态1左右移动一步,一秒一步,状态每秒都在01变换,输出从位置s到位置t的最少时间,不存在输出-1。
【思路】
bfs,根据时间和初始状态判断下不同位置在不同时间的状态即可。
教训:当判断条件比较多的时候不要集中在一起,否则很容易导致出现隐蔽的错误。
【代码】
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include<iomanip>
#include <map>
#include<set>
#include <list>
#include <vector>
#include <stack>
#include <queue>
#include <algorithm>
#define go(i,a,b) for(int i=a;i<=b;i++)
#define og(i,a,b) for(int i=a;i>=b;i--)
#define mem(a,b) memset(a,b,sizeof(a))
#define Pi acos(-1)
#define eps 1.0e-8
using namespace std;
typedef long long int ll;
typedef pair <int,int> pa;
const int maxn=1e5+5;
const int inf=0x3f3f3f3f;
const int mod=1e9+7;
map <int,int> a[maxn];
map <int,int> vis[maxn];
struct p{
int x,y;
int step;
}f;
int n,m,xx,yy;
int bfs(int x,int y)
{
queue <p> q;
while(!q.empty()) q.pop();
f.x=x,f.y=y,f.step=0;
q.push(f);
while(!q.empty())
{
f=q.front();
q.pop();
int step;
x=f.x,y=f.y,step=f.step;
if(x==xx&&y==yy) return step;
if(step&1)
{
if(a[x][y]&1)
{
if(x+1<=n&&!vis[x+1][y])
f.x=x+1,f.y=y,f.step=step+1,q.push(f),vis[x+1][y]=1;
if(x-1>0&&!vis[x-1][y])
f.x=x-1,f.y=y,f.step=step+1,q.push(f),vis[x-1][y]=1;
}
else
{
if(y+1<=m&&!vis[x][y+1])
f.x=x,f.y=y+1,f.step=step+1,q.push(f),vis[x][y+1]=1;
if(y-1>0&&!vis[x][y-1])
f.x=x,f.y=y-1,f.step=step+1,q.push(f),vis[x][y-1]=1;
}
}
else
{
if(a[x][y]&1)
{
if(y+1<=m&&!vis[x][y+1])
f.x=x,f.y=y+1,f.step=step+1,q.push(f),vis[x][y+1]=1;
if(y-1>0&&!vis[x][y-1])
f.x=x,f.y=y-1,f.step=step+1,q.push(f),vis[x][y-1]=1;
}
else
{
if(x+1<=n&&!vis[x+1][y])
f.x=x+1,f.y=y,f.step=step+1,q.push(f),vis[x+1][y]=1;
if(x-1>0&&!vis[x-1][y])
f.x=x-1,f.y=y,f.step=step+1,q.push(f),vis[x-1][y]=1;
}
}
}
return -1;
}
main()
{
int T,x,y; scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
go(i,1,n) a[i].clear(),vis[i].clear();
go(i,1,n)
go(j,1,m)
scanf("%d",&a[i][j]);
scanf("%d%d%d%d",&x,&y,&xx,&yy);
int ans=bfs(x,y);
printf("%d\n",ans);
}
}