ZOJ 4020 Traffic Lights BFS

题意:n*m矩阵a.若a[i][j]==1则可以往左右走,若a[i][j]==0 则可以往上下走.
每一秒可以按上述规则移动,并且每秒钟矩阵所有的值翻转。
n*m<=1e5.问从(sx,sy)到(tx,ty)的最短时间.


首先n*m<=1e5 开一维数组表示地图.
若地图每秒不变化 那么就是一个裸的BFS

现在地图每秒翻转 初始地图设为A 翻转的设为B.那么记录每个点状态(x,y,st(A/B),d) 

每一步权值都为1,跑BFS即可.

#include <bits/stdc++.h>
using namespace std;
const int N=2e5+5;
int T,n,m,sx,sy,tx,ty,res=1e9;
bool a[N*2],vis[N][2];
int dx[]={-1,1,0,0};
int dy[]={0,0,-1,1};
struct node{
	int x,y,st,d;
	node(){}
	node(int xx,int yy,int stt,int dd)
	{
		x=xx,y=yy,st=stt,d=dd;
	}
};
bool check(int x,int y)
{
	return (x>=0&&x<n&&y>=0&&y<m);
}
void bfs()
{
	memset(vis,0,sizeof(vis));
	queue<node> q;
	q.push(node(sx,sy,0,0));
	vis[sx*m+sy][0]=true;
	while(!q.empty())
	{
		node u=q.front();
		q.pop();
		int pos=u.x*m+u.y;
		int st=(a[pos]+u.d)%2;
		if(u.x==tx&&u.y==ty)
			res=min(res,u.d);
		for(int i=0;i<4;i++)
		{
			int nx=u.x+dx[i],ny=u.y+dy[i];
			int np=nx*m+ny,nst=1-u.st;
			if(check(nx,ny)==false)
				continue;
			if(i<2&&st==0||(i>=2&&i<4&&st))
			{
				if(!vis[np][nst])
				{
					vis[np][nst]=true;
					q.push(node(nx,ny,nst,u.d+1));
				}
			}
		}
	}
}
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	cin>>T;
	while(T--)
	{
		res=1e9;
		cin>>n>>m;
		for(int i=0;i<n;i++)
			for(int j=0;j<m;j++)
				cin>>a[i*m+j];
		cin>>sx>>sy>>tx>>ty;
		sx--,sy--,tx--,ty--;
		bfs();
		if(res>=1e9)
			res=-1;
		cout<<res<<'\n';
	}
	return 0;
} 


猜你喜欢

转载自blog.csdn.net/noone0/article/details/79864701