zoj 4020 Traffic Light(bfs)

【题目】

Traffic Light

【题意】

状态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);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值