码迷,mamicode.com
首页 > 其他好文 > 详细

ZOJ 4020 Traffic Light(BFS)

时间:2018-04-08 22:34:07      阅读:302      评论:0      收藏:0      [点我收藏+]

标签:bfs   tar   while   nod   lse   mes   using   namespace   ace   

题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=5748

题意:给定一个n x m的图,每个点初始有标记0或1。0代表只能上下走,1代表只能左右走。每秒状态翻转(0变1,1变0)。给定一个人的初始位置和其要走到的最终位置。

求最少要走多少秒,每秒一步。

题解:BFS。

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 int n,m,sx,sy,ex,ey;
 5 map < pair<int,int>,int > t;
 6 map < pair<int,int>,int > vis[2];
 7 
 8 struct node{
 9     int x,y,step;
10 };
11 
12 bool check(int x,int y,int id){
13     if(x>=1&&x<=n&&y>=1&&y<=m&&!vis[id][make_pair(x,y)]){
14         vis[id][make_pair(x,y)]=1;
15         return true;
16     }
17     return false;
18 }
19 
20 int BFS(){
21     queue <node> Q;
22     node nd;
23     nd.x=sx;nd.y=sy;nd.step=0;
24     Q.push(nd);
25     vis[0][make_pair(sx,sy)]=1;
26     while(!Q.empty()){
27         node cur=Q.front();Q.pop();
28         if(cur.x==ex&&cur.y==ey){
29             return cur.step;
30         }
31         int f=t[make_pair(cur.x,cur.y)];
32         if(cur.step%2) f^=1;
33         if(f==0){
34             node np;
35             np.x=cur.x+1;np.y=cur.y;np.step=cur.step+1;
36             if(check(np.x,np.y,0)) Q.push(np);
37             np.x=cur.x-1;
38             if(check(np.x,np.y,0)) Q.push(np);
39         }
40         else if(f==1){
41             node np;
42             np.x=cur.x;np.y=cur.y+1;np.step=cur.step+1;
43             if(check(np.x,np.y,0)) Q.push(np);
44             np.y=cur.y-1;
45             if(check(np.x,np.y,0)) Q.push(np);
46         }
47     }
48     return -1;
49 }
50 
51 int main(){
52     int T,x;
53     scanf("%d",&T);
54     while(T--){
55         scanf("%d%d",&n,&m);
56         for(int i=1;i<=n;i++)
57         for(int j=1;j<=m;j++){
58             scanf("%d",&x);
59             pair <int,int> p;
60             p.first=i;p.second=j;
61             t[p]=x;
62             vis[0][p]=vis[1][p]=0;
63         }
64         scanf("%d%d%d%d",&sx,&sy,&ex,&ey);
65         printf("%d\n",BFS());
66     }
67     return 0;
68 }

 

ZOJ 4020 Traffic Light(BFS)

标签:bfs   tar   while   nod   lse   mes   using   namespace   ace   

原文地址:https://www.cnblogs.com/Leonard-/p/8747507.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!