和上一个题基本一样。
1 #include <iostream> 2 #include <cstring> 3 #include <cstdio> 4 #include <cctype> 5 #include <queue> 6 #include <map> 7 using namespace std; 8 9 const int N = 101; 10 char maze[N][N]; 11 bool visit[N][N][1 << 4]; 12 int dx[] = { 0, 0, 1, -1 }; 13 int dy[] = { 1, -1, 0, 0 }; 14 int n, m, sx, sy; 15 map<char, int> mp; 16 17 void init() 18 { 19 mp['B'] = 0; mp['b'] = 0; 20 mp['Y'] = 1; mp['y'] = 1; 21 mp['R'] = 2; mp['r'] = 2; 22 mp['G'] = 3; mp['g'] = 3; 23 } 24 25 bool ok( int x, int y ) 26 { 27 return x >= 0 && x < n && y >= 0 && y < m; 28 } 29 30 struct Node 31 { 32 int x, y, step, state; 33 Node(){} 34 Node( int _x, int _y, int _step, int _state ) 35 { 36 x = _x, y = _y, step = _step, state = _state; 37 } 38 }; 39 40 bool uc( char ch ) 41 { 42 return ch == 'B' || ch == 'Y' || ch == 'R' || ch == 'G'; 43 } 44 45 bool lc( char ch ) 46 { 47 return ch == 'b' || ch == 'y' || ch == 'r' || ch == 'g'; 48 } 49 50 queue<Node> q; 51 52 int bfs() 53 { 54 while ( !q.empty() ) q.pop(); 55 memset( visit, false, sizeof(visit) ); 56 q.push( Node( sx, sy, 0, 0 ) ); 57 visit[sx][sy][0] = true; 58 while ( !q.empty() ) 59 { 60 Node cur = q.front(); 61 q.pop(); 62 if ( maze[cur.x][cur.y] == 'X' ) return cur.step; 63 for ( int i = 0; i < 4; i++ ) 64 { 65 int xx = cur.x + dx[i]; 66 int yy = cur.y + dy[i]; 67 if ( ok( xx, yy ) ) 68 { 69 if ( maze[xx][yy] == '#' ) continue; 70 if ( uc( maze[xx][yy] ) ) 71 { 72 int tmp = ( 1 << mp[maze[xx][yy]] ); 73 if ( ( cur.state & tmp ) && !visit[xx][yy][cur.state] ) 74 { 75 q.push( Node( xx, yy, cur.step + 1, cur.state) ); 76 visit[xx][yy][cur.state] = true; 77 } 78 } 79 else if ( lc( maze[xx][yy] ) ) 80 { 81 int tmp = ( 1 << mp[maze[xx][yy]] ); 82 if ( !visit[xx][yy][cur.state | tmp] ) 83 { 84 q.push( Node( xx, yy, cur.step + 1, cur.state | tmp ) ); 85 visit[xx][yy][cur.state | tmp] = true; 86 } 87 } 88 else 89 { 90 if ( !visit[xx][yy][cur.state] ) 91 { 92 q.push( Node( xx, yy, cur.step + 1, cur.state ) ); 93 visit[xx][yy][cur.state] = true; 94 } 95 } 96 } 97 } 98 } 99 return -1; 100 } 101 102 int main () 103 { 104 init(); 105 while ( scanf("%d%d", &n, &m) != EOF ) 106 { 107 if ( !n && !m ) break; 108 int x = 0; 109 for ( int i = 0; i < n; i++ ) 110 { 111 scanf("%s", maze[i]); 112 for ( int j = 0; j < m; j++ ) 113 { 114 if ( maze[i][j] == '*' ) 115 { 116 sx = i; 117 sy = j; 118 maze[i][j] = '.'; 119 } 120 else if ( maze[i][j] == 'X' ) 121 { 122 x++; 123 } 124 } 125 } 126 if ( x == 0 || ( x = bfs() ) == -1 ) 127 { 128 printf("The poor student is trapped! "); 129 } 130 else 131 { 132 printf("Escape possible in %d steps. ", x); 133 } 134 } 135 return 0; 136 }