NOI 题库 6264

6264  走出迷宫

描述

当你站在一个迷宫里的时候,往往会被错综复杂的道路弄得失去方向感,如果你能得到迷宫地图,事情就会变得非常简单。 
假设你已经得到了一个n*m的迷宫的图纸,请你找出从起点到出口的最短路。

输入
第一行是两个整数n和m(1<=n,m<=100),表示迷宫的行数和列数。
接下来n行,每行一个长为m的字符串,表示整个迷宫的布局。字符'.'表示空地,'#'表示墙,'S'表示起点,'T'表示出口。
输出
输出从起点到出口最少需要走的步数。
样例输入
3 3
S#T
.#.
...
样例输出
6
 1 #include "bits/stdc++.h"
 2 
 3 using namespace std ;
 4 const int maxN = 1e5 + 1e3 ;
 5 const int INF = 2147483647 ; 
 6 
 7 int start_x , start_y , des_x , des_y ;
 8 const int dx [ ] = { 1 , 0 , -1 , 0 } ;
 9 const int dy [ ] = { 0 , 1 , 0 , -1 } ;
10 
11 char mp[ 550 ][ 550 ] ;
12 int pos_x[ maxN ] , pos_y [ maxN ] ,step[ maxN ] ;
13 void Scan ( const int n , const int m ) {
14         getchar ( ) ;
15         for ( int i=1 ; i<=n ; ++i ) {
16                 for ( int j=1 ; j<=m ; ++j ) {
17                         mp[ i ][ j ] = getchar ( ) ;
18                         if ( mp [ i ][ j ] == 'S' ) {
19                                 start_x = i ; 
20                                 start_y = j ;
21                         }
22                         if( mp[ i ][ j ] == 'T' ) {
23                                 des_x = i ;
24                                 des_y = j ; 
25                                 mp[ i ][ j ] = '.' ;
26                         } 
27                 }
28                 getchar ( ) ;
29         }
30 }
31 
32 void BFS ( const int n , const int m ) {
33         int Head = 0 , Tail = 1 ; 
34         bool Get_Target = false ;
35         pos_x[ Tail ] = start_x ;
36         pos_y[ Tail ] = start_y ;
37         step[ Tail ] = 0 ;
38         mp[ start_x ][ start_y ] = '#' ;
39         while ( Head < Tail ) {
40                 ++ Head ;
41                 for ( int i=0 ; i<4 ; ++i ) {
42                         int xx = pos_x[ Head ] + dx[ i ] ;
43                         int yy = pos_y[ Head ] + dy[ i ] ;
44                         if ( xx > 0 && xx <= n && yy >= 0 && yy <= m && ( mp[ xx ][ yy ] == '.' || mp[ xx ][ yy ] == '*' ) ) {
45                                  step[ ++ Tail ] = step[ Head ] + 1 ;
46                                  mp[ xx ][ yy ] = '#' ;
47                                  pos_x [ Tail ] = xx ;
48                                  pos_y [ Tail ] = yy ; 
49                                  if ( xx == des_x && yy == des_y ) {
50                                          Get_Target = true ;
51                                          printf ( "%d\n" , step[ Tail ] ) ;
52                                  }
53                         } 
54                 }
55         }
56         if ( !Get_Target ) { printf ( "-1\n" ) ; }
57 }
58 
59 int main ( ) {
60         int N , M ;
61         scanf ( "%d%d" , &N , &M ) ;
62         Scan ( N , M ) ;
63         BFS ( N , M );
64 }
View Code

 

2016-10-19 21:00:26

posted @ 2016-10-19 21:00  SHHHS  阅读(326)  评论(0编辑  收藏  举报