Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //UVa Q589
- #include <bits/stdc++.h>
- using namespace std ;
- struct stat {
- int Bx, By, Sx, Sy;
- bool operator!=(const stat &x){return Bx != x.Bx || By != x.By || Sx != x.Sx || Sy != x.Sy;}
- }pre[20][20][20][20];
- bool maze[20][20];
- bool vis[20][20][20][20];//Bx, By, Sx, Sy
- int dx[] = {0,1,0,-1};
- int dy[] = {1,0,-1,0};
- char out[] = {'e', 's', 'w', 'n'};
- int32_t main(){
- int n,m,cnt = 0;
- stat one;
- char c;
- while(cin >> n >> m){
- if(n == 0 && m == 0)break;
- memset(vis, 0, sizeof(vis));
- memset(maze, 0, sizeof(maze));
- int Tx, Ty;
- for(int i = 0; i < n; ++i){
- for(int j = 0; j < m; ++j){
- cin >> c;
- if(c == 'S'){
- one.Sx = i;
- one.Sy = j;
- }else if(c == 'B'){
- one.Bx = i;
- one.By = j;
- }else if(c == 'T'){
- Tx = i;
- Ty = j;
- }
- maze[i][j] = (c == '#')? 1 : 0;
- }
- }
- //BFS
- deque<stat> dq, brt;
- vis[one.Bx][one.By][one.Sx][one.Sy] = 1;
- dq.emplace_back(one);
- stat tail;
- bool fnd = 0;
- while(!dq.empty() && !fnd){
- stat tmd = dq.front();
- dq.pop_front();
- if(tmd.Bx == Tx && tmd.By == Ty){
- tail = tmd;
- fnd = 1;
- break;
- }
- do{
- //cout << tmd.Bx << ' ' << tmd.By << ' ' << tmd.Sx << ' ' << tmd.Sy << endl;
- for(int i = 0; i < 4; ++i){
- int nx = tmd.Sx+dx[i], ny = tmd.Sy+dy[i];
- if(0 <= nx && nx < n && 0 <= ny && ny < m && !maze[nx][ny]){
- if(nx == tmd.Bx && ny == tmd.By){
- if(0 <= tmd.Bx+dx[i] && tmd.Bx+dx[i] < n && 0 <= tmd.By+dy[i] && tmd.By+dy[i] < m){
- stat nxt = {.Bx = tmd.Bx+dx[i], .By = tmd.By+dy[i], .Sx = nx, .Sy = ny};
- if(vis[nxt.Bx][nxt.By][nxt.Sx][nxt.Sy])continue;
- vis[nxt.Bx][nxt.By][nxt.Sx][nxt.Sy] = 1;
- pre[nxt.Bx][nxt.By][nxt.Sx][nxt.Sy] = tmd;
- dq.emplace_back(nxt);
- if(nxt.Bx == Tx && nxt.By == Ty){
- tail = nxt;
- fnd = 1;
- break;
- }
- }
- }else{
- stat nxt = {.Bx = tmd.Bx, .By = tmd.By, .Sx = nx, .Sy = ny};
- if(vis[nxt.Bx][nxt.By][nxt.Sx][nxt.Sy])continue;
- vis[nxt.Bx][nxt.By][nxt.Sx][nxt.Sy] = 1;
- pre[nxt.Bx][nxt.By][nxt.Sx][nxt.Sy] = tmd;
- brt.emplace_back(nxt);
- }
- }
- }
- if(!brt.empty()){
- tmd = brt.front();
- brt.pop_front();
- }else break;
- }while(1);
- }
- cout << "Maze #" << ++cnt << "\n";
- if(fnd){
- vector<stat> v;
- while(tail != one){
- v.emplace_back(tail);
- //cout << tail.Bx << ' ' << tail.By << ' ' << tail.Sx << ' ' << tail.Sy << endl;
- tail = pre[tail.Bx][tail.By][tail.Sx][tail.Sy];
- }
- //cout << tail.Bx << ' ' << tail.By << ' ' << tail.Sx << ' ' << tail.Sy << endl;
- while(!v.empty()){
- for(int i = 0; i < 4; ++i){
- if(tail.Sx+dx[i] == v.back().Sx && tail.Sy+dy[i] == v.back().Sy){
- c = out[i];
- if(tail.Bx != v.back().Bx || tail.By != v.back().By)c -= 32;
- cout << c;
- break;
- }
- }
- tail = v.back();
- v.pop_back();
- }
- cout << '\n';
- }else{
- cout << "Impossible.\n";
- }
- cout << '\n';
- }
- return 0 ;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement