题意:n行m列,每个位置都有一个数字0或者1(路灯的状态,有且仅有这两种状态),0代表只能从这个位置往上走或者往下走,即( i+1 ,j )或( i-1 ,j ),1代表只能从这个位置往右走或者往左走,即( i ,j+1 )或( i ,j-1 ),每走一步,所有位置上的路灯的状态都会发生改变,即1变0,0变1。
问:从起始位置到目的位置最少需要走几步。
思路:其实就是一个简单的BFS(广搜),但是n×m<=1e5,不能直接用二维数组,可以改用vector。
代码:
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <sstream>
#include <cstdio>
#include <vector>
#include <string>
#include <cmath>
#include <stack>
#include <queue>
#include <map>
#include <set>
#define MAX 0x3f3f3f3f
#define LL long long int
#define fori(a,b) for(int i=a;i<=b;i++)
#define forj(a,b) for(int j=a;j<=b;j++)
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
const double PI = acos(-1);
const int M=1e5+10;
LL sx,sy,ex,ey,n,m;
LL d[2]={1,-1};
struct node{
LL x,y;
LL time=0;
}st;
queue<node>q;
vector<LL>v[M],vis[M];
LL bfs()
{
while(!q.empty()){
q.pop();
}
st.x=sx;
st.y=sy;
st.time=0;
vis[sx][sy]=1;
q.push(st);
while(!q.empty()){
node now=q.front();
q.pop();
if(now.x==ex&&now.y==ey)
return now.time;
LL state=v[now.x][now.y]^(now.time%2); //time为偶数,该位置状态不变,奇数则该位置状态改变
if(!state){
for(LL i=0;i<2;i++){
st.x=now.x+d[i];
st.y=now.y;
st.time=now.time+1;
if(st.x>=0&&st.x<n&&st.y>=0&&st.y<m&&!vis[st.x][st.y]){
vis[st.x][st.y]=1;
q.push(st);
}
}
}
else {
for(LL i=0;i<2;i++){
st.x=now.x;
st.y=now.y+d[i];
st.time=now.time+1;
if(st.x>=0&&st.x<n&&st.y>=0&&st.y<m&&!vis[st.x][st.y]){
vis[st.x][st.y]=1;
q.push(st);
}
}
}
}
return -1;
}
int main()
{
//freopen("//home//acm//桌面//in","r",stdin);
LL t;
cin >> t;
while(t--){
cin >> n >> m;
for(LL i=0;i<n;i++){ //清空
v[i].clear();
vis[i].clear();
for(int j=0;j<m;j++){
vis[i].push_back(0); //清零
}
}
LL s;
for(LL i=0;i<n;i++){
for(LL j=0;j<m;j++){
cin >> s;
v[i].push_back(s);
}
}
cin >> sx >> sy >> ex >> ey;
sx--,sy--,ex--,ey--;
cout << bfs() << endl;
}
return 0;
}