我感觉就是一个走迷宫的题,只不过这个的墙是变化的。但是因为一直在0-1之间转换,所以把走到当前位置的步数进行判断,如果是奇数就把当前位置的灯状态改变,偶数不用处理,然后就是基本的搜索了。
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5+10;
vector<int>mp[maxn];
vector<int>vis[maxn];
vector<int>step[maxn];
int n,m,si,sj,ei,ej;
typedef pair<int,int> pq;
int Bfs()
{
queue <pq> que;
while(!que.empty())
que.pop();
pq tmp;
tmp.first = si;
tmp.second = sj;
que.push(tmp);
step[si][sj] = 0;
vis[si][sj] = 0;
while(!que.empty())
{
pq top = que.front();
que.pop();
if(top.first == ei && top.second == ej)
return step[top.first][top.second];
int next_x,next_y;
int pp = step[top.first][top.second];
if(pp & 1)
mp[top.first][top.second] = !mp[top.first][top.second];
if(mp[top.first][top.second] == 0)
{
for(int i = 1;i <= 2; i++)
{
if(i == 1)
{
next_x = top.first + 1;
next_y = top.second;
}
else if(i == 2)
{
next_x = top.first - 1;
next_y = top.second;
}
if(next_x >= 1 && next_x <= n && next_y >= 1 && next_y <= m && !vis[next_x][next_y])
{
pq dui;
dui.first = next_x;
dui.second = next_y;
que.push(dui);
vis[next_x][next_y] = 1;
step[next_x][next_y] = pp + 1;
}
}
}
else if(mp[top.first][top.second] == 1)
{
for(int i = 1;i <= 2; i++)
{
if(i == 1)
{
next_x = top.first;
next_y = top.second + 1;
}
else if(i == 2)
{
next_x = top.first;
next_y = top.second - 1;
}
if(next_x >= 1 && next_x <= n && next_y >= 1 && next_y <= m && !vis[next_x][next_y])
{
pq dui;
dui.first = next_x;
dui.second = next_y;
que.push(dui);
vis[next_x][next_y] = 1;
step[next_x][next_y] = pp + 1;
}
}
}
}
return -1;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d %d",&n,&m);
for(int i = 1;i <= n; i++)
{
mp[i].clear();
vis[i].clear();
step[i].clear();
mp[i].resize(m+5);
vis[i].resize(m+5);
step[i].resize(m+5);
for(int j = 1;j <= m; j++)
scanf("%d",&mp[i][j]);
}
scanf("%d %d %d %d",&si,&sj,&ei,&ej);
printf("%d\n",Bfs());
}
return 0;
}
标签:int,Light,ZOJ,next,second,que,Traffic,top,first From: https://blog.51cto.com/u_16131191/6356110