洛谷P1649 [USACO07OCT]障碍路线Obstacle Course BFS 最小转弯

洛谷P1649 [USACO07OCT]障碍路线Obstacle Course   BFS 最小转弯

 

 1 #include <cstdio> 
 2 #include <cmath>
 3 #include <cstdlib>
 4 #include <cstring>
 5 #include <iostream> 
 6 #include <iomanip> 
 7 #include <string> 
 8 #include <algorithm> 
 9 #define LL long long 
10 #define For(i,j,k) for(int i=j;i<=k;i++) 
11 #define Dow(i,j,k) for(int i=j;i>=k;i--) 
12 using namespace std ;  
13 
14 const int N = 111 ; 
15 const int dx[4]={1,0,-1,0} ; 
16 const int dy[4]={0,1,0,-1} ; 
17 struct node{
18     int x,y,dir,step ; 
19 }q[40011];
20 int n,sx,sy,tx,ty,h,t ; 
21 bool visit[4][N][N],flag[N][N] ; 
22 char s[3] ; 
23 
24 inline int read() 
25 {
26     int x = 0 , f = 1 ; 
27     char ch = getchar() ; 
28     while(ch<'0'||ch>'9') { if(ch=='-') f = -1 ; ch = getchar(); } 
29     while(ch>='0'&&ch<='9') { x = x * 10+ch-48 ; ch = getchar(); } 
30     return x * f ; 
31 }
32 
33 inline void bfs(int x,int y) 
34 {
35     h = 0 ; t = 0 ; 
36     q[++t].x = x ; q[t].y = y ; q[t].dir = 0 ; visit[0][x][y] = 1 ; 
37     q[++t].x = x ; q[t].y = y ; q[t].dir = 1 ; visit[1][x][y] = 1 ; 
38     q[++t].x = x ; q[t].y = y ; q[t].dir = 2 ; visit[2][x][y] = 1 ; 
39     q[++t].x = x ; q[t].y = y ; q[t].dir = 3 ; visit[3][x][y] = 1 ; 
40     while(h<t) {
41         int xx,yy,d,st ; 
42         x = q[++h].x ; y=q[h].y ; d=q[h].dir ; st=q[h].step ; 
43         For(i,1,n) {
44             xx = x+dx[d]*i ; 
45             yy = y+dy[d]*i ; 
46             if(xx<1||xx>n||yy<1||yy>n||flag[xx][yy]) break ;    //
47             if(visit[d][xx][yy]) continue ; //
48             visit[d][xx][yy] = 1 ; 
49             q[++t].x = xx ; q[t].y = yy ; q[t].dir=d ; q[t].step=st ; 
50             if(xx==tx&&yy==ty) {
51                 printf("%d\n",q[t].step) ; 
52                 return ; 
53             }
54         }
55         d = (d+1)%4 ; 
56         if(!visit[d][x][y])  {
57             visit[d][x][y] = 1 ; 
58             q[++t].x = x ; q[t].y = y ; q[t].dir = d ; q[t].step = st+1 ; 
59         }
60         d = (d+2)%4 ; 
61         if(!visit[d][x][y]) {
62             visit[d][x][y] = 1 ; 
63             q[++t].x = x ; q[t].y = y ; q[t].dir = d ; q[t].step = st+1 ; 
64         }
65     }
66     printf("-1\n") ; 
67 }
68 
69 int main() 
70 {
71     n = read() ; 
72     For(i,1,n) {
73         For(j,1,n) {
74             scanf("%s",s+1) ;  
75             if(s[1]=='x') flag[i][j]=1 ; 
76             if(s[1]=='A') sx = i , sy = j ; 
77             if(s[1]=='B') tx = i , ty = j ; 
78         }
79     }
80     bfs(sx,sy) ; 
81     return 0 ; 
82 }

 

posted @ 2017-10-03 11:52  third2333  阅读(308)  评论(0编辑  收藏  举报