ZOJ 4020 Traffic Light(BFS)

题目链接

题意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;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值