思路
这个题的思路很清楚,只不过第一次用到了三维数组。记录一下吧。
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
int sx,sy,fx,fy;
int n,m;
int dir[2][2][2] = {{{1,0},{-1,0}},{{0,1},{0,-1}} } ;
struct node {
int x,y,s;
node( int _x,int _y,int _s) {
x = _x; y = _y; s = _s;
}
};
vector<int> vis[N];
vector<int> edges[N];
int bfs() {
queue<node> que;
vis[sx][sy] = 1;
que.push( node(sx,sy,0) ) ;
int ans = -1;
while ( !que.empty() ) {
node t = que.front();
que.pop();
if ( t.x==fx && t.y==fy ) {
ans = t.s;
break;
}
int step = t.s;
int tx,ty;
for ( int i=0; i<2; i++ ) {
tx = t.x+dir[(step+edges[t.x][t.y])%2][i][0];
ty = t.y+dir[(step+edges[t.x][t.y])%2][i][1];
if ( tx>=0 && ty>=0&& tx<n&&ty<m && !vis[tx][ty] ) {
vis[tx][ty] = 1;
que.push( node( tx,ty,step+1 ) ) ;
}
}
}
return ans;
}
int main()
{
int T;
cin>>T;
while (T--) {
scanf("%d%d",&n,&m);
for ( int i=0; i<n; i++ )
edges[i].clear(),vis[i].clear();
for ( int i=0; i<n; i++ ) {
for (int j=0; j<m; j++ ) {
int flag;
scanf("%d",&flag);
edges[i].push_back( flag );
vis[i].push_back( 0 ) ;
}
}
scanf("%d%d%d%d",&sx,&sy,&fx,&fy);
--sx,--sy,--fx,--fy;
int ans = bfs();
printf("%d\n",ans);
}
return 0;
}