# bzoj1644 / P1649 [USACO07OCT]障碍路线Obstacle Course

P1649 [USACO07OCT]障碍路线Obstacle Course

bfs

 1 #include<iostream>
2 #include<cstdio>
3 #include<cstring>
4 #include<queue>
5 using namespace std;
6 #define pi pair<int,int>
7 #define mkp make_pair
8 #define N 105
9 const int d1[4]={0,1,0,-1};
10 const int d2[4]={1,0,-1,0};
11 char q[3]; bool dan[N][N];
12 int a[N][N],vis[N][N],n;
13 pi S,T; queue<pi> h;
14 int main(){
15     scanf("%d",&n);
16     for(int i=1;i<=n;++i){
17         for(int j=1;j<=n;++j){
18             scanf("%s",q);
19             if(q[0]=='A') S=mkp(i,j);
20             if(q[0]=='B') T=mkp(i,j);
21             if(q[0]=='x') dan[i][j]=1;
22         }
23     }h.push(S);
24     while(!h.empty()){
25         pi u=h.front(); h.pop();
26         for(int i=0;i<4;++i){
27             int r1=u.first+d1[i],r2=u.second+d2[i];
28             while(!dan[r1][r2]){
29                 if(r1>n||r1<1||r2>n||r2<1) break;
30                 if(vis[r1][r2]){
31                     r1+=d1[i];r2+=d2[i];
32                     continue;
33                 }
34                 vis[r1][r2]=vis[u.first][u.second]+1;
35                 if(mkp(r1,r2)==T){
36                     printf("%d",max(0,vis[r1][r2]-1));
37                     return 0;
38                 }h.push(mkp(r1,r2));
39                 r1+=d1[i];r2+=d2[i];
40             }
41         }
42     }printf("-1");
43     return 0;
44 }
P1649
 1 #include<iostream>
2 #include<cstdio>
3 #include<cstring>
4 #include<queue>
5 using namespace std;
6 #define pi pair<int,int>
7 #define mkp make_pair
8 #define N 105
9 const int d1[4]={0,1,0,-1};
10 const int d2[4]={1,0,-1,0};
11 char q[N]; bool dan[N][N];
12 int a[N][N],vis[N][N],n;
13 pi S,T; queue<pi> h;
14 int main(){
15     scanf("%d",&n);
16     for(int i=1;i<=n;++i){
17         scanf("%s",q);
18         for(int j=1;j<=n;++j){
19             if(q[j-1]=='A') S=mkp(i,j);
20             if(q[j-1]=='B') T=mkp(i,j);
21             if(q[j-1]=='x') dan[i][j]=1;
22         }
23     }h.push(S);
24     while(!h.empty()){
25         pi u=h.front(); h.pop();
26         for(int i=0;i<4;++i){
27             int r1=u.first+d1[i],r2=u.second+d2[i];
28             while(!dan[r1][r2]){
29                 if(r1>n||r1<1||r2>n||r2<1) break;
30                 if(vis[r1][r2]){
31                     r1+=d1[i];r2+=d2[i];
32                     continue;
33                 }vis[r1][r2]=vis[u.first][u.second]+1;
34                 if(mkp(r1,r2)==T){
35                     printf("%d",max(0,vis[r1][r2]-1));
36                     return 0;
37                 }h.push(mkp(r1,r2));
38                 r1+=d1[i];r2+=d2[i];
39             }
40         }
41     }
42 }
bzoj1644

posted @ 2018-11-28 13:53  kafuuchino  阅读(121)  评论(0编辑  收藏  举报