HDU-2102 A计划 BFS
生活随笔
收集整理的這篇文章主要介紹了
HDU-2102 A计划 BFS
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
A計劃
Time Limit: 3000/1000 MS (Java/Others)????Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4156????Accepted Submission(s): 936
現據密探 所報,公主被關在一個兩層的迷宮里,迷宮的入口是S(0,0,0),公主的位置用P表示,時空傳輸機用#表示,墻用*表示,平地用.表示。騎士們一進入時 空傳輸機就會被轉到另一層的相對位置,但如果被轉到的位置是墻的話,那騎士們就會被撞死。騎士們在一層中只能前后左右移動,每移動一格花1時刻。層間的移 動只能通過時空傳輸機,且不需要任何時間。 Input 輸入的第一行C表示共有C個測試數據,每個測試數據的前一行有三個整數N,M,T。 N,M迷宮的大小N*M(1 <= N,M <=10)。T如上所意。接下去的前N*M表示迷宮的第一層的布置情況,后N*M表示迷宮第二層的布置情況。 Output 如果騎士們能夠在T時刻能找到公主就輸出“YES”,否則輸出“NO”。 Sample Input 1
5 5 14
S*#*.
.#...
.....
****.
...#.
..*.P
#.*..
***..
...*.
*.#.. Sample Output YES 簡單BFS,題目雖說是在T時刻解救公主,但其實只要在小于T時刻的時間內解救了公主就可以了,因為題并沒有說走過的邊不能夠往回走,所以時間變成了小于等于T。 代碼如下: #include <cstdio> #include <cstdlib> #include <cstring> #include <queue> using namespace std;char map[2][15][15], hash[2][15][15];int sx, sy, ex, ey, sk, ek, S;inline bool legal( char c ) {if( c== '.'|| c== 'S'|| c== '#'|| c== '*'|| c== 'P' ){return true;}return false; }inline void gchar( char &c ) {char t;while( t= getchar(), !legal( t ) ) ;c= t; } struct Node {int x, y, k, step; }info;int dis[4][2]= { 0, 1, 0, -1, 1, 0, -1, 0 };bool BFS( ) {memset( hash, 0, sizeof( hash ) ); // 不能單純的判斷某一點是否走過,而是該點是否有更優的解queue< Node >q;info.x= sx, info.y= sy, info.k= sk, info.step= 0;hash[sk][sx][sy]= 1;q.push( info );int cnt= 0;while( !q.empty() ){Node pos= q.front();q.pop();if( map[pos.k][pos.x][pos.y]== 'P'&& pos.step<= S ){// printf( "step= %d\n", pos.step );return true;}for( int i= 0; i< 4; ++i ){int x= pos.x+ dis[i][0], y= pos.y+ dis[i][1], k= pos.k, step= pos.step;if( map[k][x][y]!= 0&& map[k][x][y]!= '*' ){if( map[k][x][y]!= '#'&& !hash[k][x][y]&& step< S ){// 其已走步數不能已經到達了S步info.x= x, info.y= y, info.k= k, info.step= step+ 1;hash[k][x][y]= 1;q.push( info );}else if( map[k][x][y]== '#'&& map[ ( k+ 1 )% 2 ][x][y]!= '*'&& map[ ( k+ 1 )% 2 ][x][y]!= '#'&& !hash[ ( k+ 1 )% 2 ][x][y]&& step< S ){// 進行圖之間的轉化,但是不能夠對應在下一個圖中的墻info.x= x, info.y= y, info.k= ( k+ 1 )% 2, info.step= step+ 1;hash[ ( k+ 1 )% 2 ][x][y]= 1;q.push( info );}}}}return false; }int main( ) {int T;scanf( "%d", &T );while( T-- ){int N, M;scanf( "%d %d %d", &N, &M, &S );memset( map, 0, sizeof( map ) );for( int k= 0; k< 2; ++k ){for( int i= 1; i<= N; ++i ){for( int j= 1; j<= M; ++j ){gchar( map[k][i][j] );if( map[k][i][j]== 'S' ){sx= i, sy= j, sk= k;}if( map[k][i][j]== 'P' ){ex= i, ey= j, ek= k;}}}}printf( BFS( )? "YES\n": "NO\n" );} }
轉載于:https://www.cnblogs.com/Lyush/archive/2011/08/08/2131093.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的HDU-2102 A计划 BFS的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: windows2008的功能介紹及其与2
- 下一篇: web 服务器