![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
1 #include<cstdio> 2 #include<cstdlib> 3 #include<queue> 4 #include<iostream> 5 #include<cstring> 6 7 using namespace std; 8 9 typedef struct 10 { 11 int x, y; 12 int step; 13 }Point; 14 15 priority_queue<Point> q; 16 bool operator<(Point a, Point b) 17 { 18 return a.step > b.step; 19 } 20 21 char map[301][301]; 22 int visit[301][301]; 23 int N, M, ok, si, sj; 24 int dx[4] = {1,-1,0,0}; 25 int dy[4] = {0,0,1,-1}; 26 27 int True(Point v) 28 { 29 if(v.x>=0 && v.x<M && v.y>=0 && v.y<N) 30 return 1; 31 return 0; 32 } 33 34 int main() 35 { 36 int i,j,di,dj; 37 Point start,target; 38 39 while(scanf("%d%d",&M,&N)!=EOF) 40 { 41 getchar(); 42 if(M==0&&N==0) break; 43 for(i=0; i<M; i++) 44 { 45 scanf("%s",map[i]); 46 getchar(); 47 } 48 for(i=0; i<M; i++) 49 for(j=0; j<N; j++) 50 { 51 if(map[i][j]=='Y') 52 { 53 si = i; 54 sj = j; 55 } 56 if(map[i][j]=='T') 57 { 58 di = i; 59 dj = j; 60 } 61 } 62 memset(visit,0,sizeof(visit)); 63 start.x = si; 64 start.y = sj; 65 start.step = 0; 66 ok = 0; 67 visit[start.x][start.y] = 1; 68 q.push(start); 69 while( !q.empty() ) 70 { 71 Point u = q.top(); 72 q.pop(); 73 if(u.x==di&&u.y==dj) 74 { 75 ok = 1; 76 printf("%d\n",u.step); 77 break; 78 } 79 for(i=0; i<4; i++) 80 { 81 Point v; 82 v.x = u.x + dx[i]; 83 v.y = u.y + dy[i]; 84 if(True(v)&&!visit[v.x][v.y]&&map[v.x][v.y]!='S'&&map[v.x][v.y]!='R') 85 { 86 if(map[v.x][v.y]=='B') 87 v.step = u.step + 2; 88 else 89 v.step = u.step + 1; 90 visit[v.x][v.y] = 1; 91 q.push(v); 92 } 93 } 94 } 95 while(!q.empty()) 96 { 97 q.pop(); 98 } 99 if(!ok) 100 printf("-1\n"); 101 } 102 return 0; 103 } 104