Problem:
Problem 06:
Ghost Buster!
一般人には知る由も無いことだが、この街は幽霊で溢れている。そのほとんどは無害なのだが、困ったことに、人を呪う悪霊も少なからずいるのだ。
あるところに、そんな悪霊と戦う少女がいた。彼女は昼間は何食わぬ顔で高校に通いながらも、夜になると街中を歩き回り、彷徨える魂を見付けては成仏させるのだ。
幽霊を成仏させるためにはまずその幽霊に接近する必要があるのだが、それは簡単なことではない。幽霊は物をすり抜けられるからだ。幽霊は民家に壁から侵入して勝手口から出て行ったり、信号の無い大通りを悠々と横断したりする。人間である彼女にはそんなことはできないので、幽霊を追跡するのはとても難しいのだ。
彼女は経験上、幽霊が規則的な動きをすることを知っていた。そこで彼女は、この情報を活用して幽霊を追跡することを考えた。
彼女のいる街は、(
H
×
W
)マスのグリッドとして表される。彼女も幽霊も、1分間に1回、次の5つの行動
東へ1マス進む
西へ1マス進む
南へ1マス進む
北へ1マス進む
その場に留まる
のうちどれか1つを行うことができる。ただし、彼女は街の周囲に結界を張ったので、彼女も幽霊も街の外に出ることはできない。また、そのような行動をしようとした場合、代わりにその場に留まる。
それぞれのマスは '
#
' または '
.
' という文字によって表され、前者は幽霊だけが進入できるマスを、後者は両者が進入できるマスを表す。
幽霊の行動パターンは、L個の行動の列として与えられる。幽霊はこれらの行動を最初から順番に実行していき、全ての行動を実行し終わるとまた最初の行動に戻り、順に実行し続ける。
彼女と幽霊が N 分後に同じマスにいたならば、彼女と幽霊は時刻 N で遭遇したと言うことが出来る。幽霊は放っておくとどんな被害をもたらすか分からないので、彼女は出来るだけ早い時刻に幽霊を捕まえたい。なので、彼女は頼れる先輩であるあなたに、彼女と幽霊が遭遇できる最も早い時刻とその遭遇場所を求めるプログラムを書いてほしいと思っている。
さあ、彼女を助けて、彼女のありがたい言葉で彷徨える魂を極楽浄土へと導くのだ！
Input
複数のデータセットが与えられる。
各データセットの形式を以下に示す。
H W
（グリッドの南北方向のマスの数、グリッドの東西方向のマスの数：　空白区切りの２つの整数）
H × W
の文字　（マスの種類：'
.
', '
#
', '
A
', または '
B
'）
pattern
（幽霊の行動パタン：文字列）
'
A
' は少女の初期位置、'
B
' は幽霊の初期位置を示す。両者の初期位置は、 '
.
' のマスの上にある。
pattern
は '
5
', '
2
', '
4
', '
6
', '
8
' から成る文字列で、各文字の意味は以下の通りである：
'
5
'
その場に留まる
'
8
'
北に1マス進む
'
6
'
東に1マス進む
'
4
'
西に1マス進む
'
2
'
南に1マス進む
例えば、
pattern
が "
8544
" の場合、幽霊は「北に1マス進む」「その場に留まる」「西に1マス進む」「西に1マス進む」の行動パタンを繰り返す。
H
,
W
は 1 以上 20 以下であり、
pattern
の長さは 10 以下である。
H
,
W
がともに 0 のとき、入力は終了する。
Output
もし少女が幽霊と遭遇できるならば、最も早い遭遇時刻と、その遭遇場所の南北方向の座標、東西方向の座標を空白で区切って1行に出力せよ。グリッドの最北西を座標(0, 0)とし、最南東を座標(
H
-1,
W
-1) とする。
どのように行動しても絶対に遭遇できない場合は、 "
impossible
" と出力せよ。
Sample Input
4 7
A#...#B
.#.#.#.
.#.#.#.
...#...
5
4 7
A#...#B
.#.#.#.
.#.#.#.
...#...
2
4 7
A#...#B
.#.#.#.
.#.#.#.
...#...
4
4 7
A#...#B
.#.#.#.
.#.#.#.
...#...
442668
1 10
A#.......B
55555554
1 10
A#.......B
55555555
0 0
Output for the Sample Input
18 0 6
15 3 6
6 0 0
14 0 4
72 0 0
impossible

Submitted solutions:

code_snippet: #pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef unsigned long long int ull;

mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
ll myRand(ll B) { return (ull)rng() % B; }

int dp[20][20][20][20][10];
int dx[] = {-1, 0, 0, 1, 0};
int dy[] = {0, 1, -1, 0, 0};

int main() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    int h, w;
    while (cin >> h >> w, h + w) {
        vector<string> s(h);
        pair<int, int> S, T;
        for (int i = 0; i < h; ++i) {
            cin >> s[i];
            for (int j = 0; j < w; ++j) {
                if (s[i][j] == 'A') {
                    S = {i, j};
                    s[i][j] = '.';
                }
                if (s[i][j] == 'B') {
                    T = {i, j};
                    s[i][j] = '.';
                }
            }
        }
        string op;
        cin >> op;
        int m = op.size();
        for (int i = 0; i < h; ++i) {
            for (int j = 0; j < w; ++j) {
                for (int k = 0; k < h; ++k) {
                    for (int l = 0; l < w; ++l) {
                        for (int n = 0; n < m; ++n) {
                            dp[i][j][k][l][n] = 1e9;
                        }
                    }
                }
            }
        }
        using P = pair<int, int>;
        queue<pair<pair<P, P>, int>> q;
        dp[S.first][S.second][T.first][T.second][0] = 0;
        q.push({{S, T}, 0});
        auto mv = [&](P pos, int dx, int dy, bool b) -> P {
            auto [x, y] = pos;
            x += dx, y += dy;
            if (0 <= x and x < h and 0 <= y and y < w and (s[x][y] == '.' or b)) {
                return {x, y};
            } else {
                return {x - dx, y - dy};
            }
        };
        while (q.size()) {
            auto p = q.front();
            q.pop();
            auto a = p.first.first;
            auto b = p.first.second;
            int j = p.second;
            int cost = dp[a.first][a.second][b.first][b.second][j];
            int nj = (j + 1 == m ? 0 : j + 1);
            int k;
            if (op[j] == '5') k = 4;
            else k = (8 - (op[j] - '0')) / 2;
            for (int i = 0; i < 5; ++i) {
                auto na = mv(a, dx[i], dy[i], false);
                auto nb = mv(b, dx[k], dy[k], true);
                if (dp[na.first][na.second][nb.first][nb.second][nj] > cost + 1) {
                    dp[na.first][na.second][nb.first][nb.second][nj] = cost + 1;
                    q.push({{na, nb}, nj});
                }
            }
        }
        int res = 1e9;
        P pos;
        for (int i = 0; i < h; ++i) {
            for (int j = 0; j < w; ++j) {
                for (int k = 0; k < m; ++k) {
                    if (res > dp[i][j][i][j][k]) {
                        res = dp[i][j][i][j][k];
                        pos = {i, j};
                    }
                }
            }
        }
        if (res == 1e9) cout << "impossible\n";
        else cout << res << " " << pos.first << " " << pos.second << "\n";
    }
}
accuracy: 1
time_ms: 10
memory_kb: 9652
final_rank: 14

code_snippet: // 幅優先全ルート探索
#include <bits/stdc++.h>

using namespace std;

using Pos = pair<int, int>;
using VI = vector<int>;
using Deq = deque<pair<Pos, int>>;

// 幽霊の次の位置を返す
int NextB(int pos, char d, int h, int w) {
    switch (d) {
        case '8':
            if (pos / w - 1 >= 0) pos -= w;
            break;
        case '4':
            if (pos % w - 1 >= 0) pos--;
            break;
        case '2':
            if (pos / w + 1 < h) pos += w;
            break;
        case '6':
            if (pos % w + 1 < w) pos++;
            break;
        default:
            break;
    }
    return pos;
}
// 少女の次の位置を返す
int NextA(int pos, VI& grid, char d, int h, int w) {
    switch (d) {
        case '8':
            if (pos / w - 1 >= 0 && grid[pos - w] == 1) pos -= w;
            break;
        case '4':
            if (pos % w - 1 >= 0 && grid[pos - 1] == 1) pos--;
            break;
        case '2':
            if (pos / w + 1 < h && grid[pos + w] == 1) pos += w;
            break;
        case '6':
            if (pos % w + 1 < w && grid[pos + 1] == 1) pos++;
            break;
        default:
            break;
    }
    return pos;
}
int main() {
    while (true) {
        int h, w;
        cin >> h >> w;
        if (h == 0 && w == 0) break;
        VI grid(h * w);
        int a_pos, b_pos;
        for (int i = 0; i < h; ++i) {
            for (int j = 0; j < w; ++j) {
                char c;
                cin >> c;
                if (c == 'A') {
                    a_pos = i * w + j;
                    grid[i * w + j] = 1;
                } else if (c == 'B') {
                    b_pos = i * w + j;
                    grid[i * w + j] = 1;
                } else if (c == '.') {
                    grid[i * w + j] = 1;
                } else if (c == '#') {
                    grid[i * w + j] = 0;
                }
            }
        }
        string pattern;
        cin >> pattern;

        // マスの訪問時間を管理するテーブル(未訪問:-1)
        vector<vector<vector<int>>> visited(h * w,
            vector<vector<int>>(h * w, vector<int>(pattern.length(), -1)));
        char direction[] = {'5', '8', '6', '4', '2'};  // 少女の移動方向
        Deq dq;
        dq.push_back(make_pair(make_pair(a_pos, b_pos), -1));
        bool flg = true;
        while (!dq.empty()) {
            pair<Pos, int> p = dq.front();
            dq.pop_front();
            if (p.first.first == p.first.second) {
                cout << visited[p.first.first][p.first.second][p.second] << " "
                     << p.first.first / w << " " << p.first.first % w << endl;
                flg = false;
                break;
            } else {
                // 幽霊の次の行動パターン
                int turn = (p.second + 1) % pattern.length();
                // 幽霊の次の位置
                b_pos = NextB(p.first.second, pattern[turn], h, w);
                // 少女の次の位置
                for (int i = 0; i < 5; ++i) {
                    a_pos = NextA(p.first.first, grid, direction[i], h, w);
                    if (visited[a_pos][b_pos][turn] == -1) {
                        dq.push_back(make_pair(make_pair(a_pos, b_pos), turn));
                        visited[a_pos][b_pos][turn] =
                            visited[p.first.first][p.first.second][p.second] +
                            1;
                    }
                }
            }
        }
        if (flg) cout << "impossible" << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 90
memory_kb: 14516
final_rank: 20

code_snippet: #include <stdio.h>
#include <cmath>
#include <algorithm>
#include <cfloat>
#include <stack>
#include <queue>
#include <vector>
typedef long long int ll;
#define BIG_NUM 2000000000
#define MOD 1000000007
#define EPS 0.000001
using namespace std;

int H,W;

int diff_row[5] = {-1,0,0,1,0},diff_col[5] = {0,-1,1,0,0};
char map[20][21],pattern[11];
bool***** check;

struct Info{
	int my_row,my_col,my_time,enemy_row,enemy_col;
};

bool rangeCheck(int row,int col){
	if(row >= 0 && row <= H-1 && col >= 0 && col <= W-1)return true;
	else{
		return false;
	}
}


int main(){

	bool FLG;
	int ans_row,ans_col,ans_time,next_my_row,next_my_col,next_enemy_row,next_enemy_col,pattern_length,tmp;
	check = new bool****[20];
	for(int i = 0; i < 20; i++){
		check[i] = new bool***[20];
		for(int a = 0; a < 20; a++){
			check[i][a] = new bool**[20];
			for(int b = 0; b < 20; b++){
				check[i][a][b] = new bool*[20];
				for(int c = 0; c < 20; c++)check[i][a][b][c] = new bool[10];
			}
		}
	}

	while(true){
		scanf("%d %d",&H,&W);
		if(H == 0 && W == 0)break;

		FLG = false;
		Info first;

		first.my_time = 0;

		for(int a = 0; a < H; a++){
			for(int b = 0; b < W; b++){
				for(int c = 0; c < H; c++){
					for(int d = 0; d < W; d++){
						for(int e = 0; e < 10;e++)check[a][b][c][d][e] = false;
					}
				}
			}
		}

		for(int i = 0; i < H; i++){
			scanf("%s",map[i]);
			for(int k = 0; k < W; k++){
				switch(map[i][k]){
				case 'A':
					first.my_row = i;
					first.my_col = k;
					break;
				case 'B':
					first.enemy_row = i;
					first.enemy_col = k;
					break;
				default:break;

				}
			}
		}

		scanf("%s",pattern);
		for(pattern_length = 0; pattern[pattern_length] != '\0';pattern_length++);

		queue<Info> Q;

		Q.push(first);

		while(!Q.empty()){

			if(Q.front().my_row == Q.front().enemy_row && Q.front().my_col == Q.front().enemy_col){
				FLG = true;
				ans_row = Q.front().my_row;
				ans_col = Q.front().my_col;
				ans_time = Q.front().my_time;
				break;
			}

			Q.front().my_time++;

			tmp = (Q.front().my_time-1+pattern_length)%pattern_length;
			switch(pattern[tmp]){
			case '5':
				next_enemy_row = Q.front().enemy_row;
				next_enemy_col = Q.front().enemy_col;
				break;
			case '2':
				if(rangeCheck(Q.front().enemy_row+1,Q.front().enemy_col)){
					next_enemy_row = Q.front().enemy_row+1;
					next_enemy_col = Q.front().enemy_col;
				}else{
					next_enemy_row = Q.front().enemy_row;
					next_enemy_col = Q.front().enemy_col;
				}
				break;
			case '4':
				if(rangeCheck(Q.front().enemy_row,Q.front().enemy_col-1)){
					next_enemy_row = Q.front().enemy_row;
					next_enemy_col = Q.front().enemy_col-1;
				}else{
					next_enemy_row = Q.front().enemy_row;
					next_enemy_col = Q.front().enemy_col;
				}
				break;
			case '6':
				if(rangeCheck(Q.front().enemy_row,Q.front().enemy_col+1)){
					next_enemy_row = Q.front().enemy_row;
					next_enemy_col = Q.front().enemy_col+1;
				}else{
					next_enemy_row = Q.front().enemy_row;
					next_enemy_col = Q.front().enemy_col;
				}
				break;
			case '8':
				if(rangeCheck(Q.front().enemy_row-1,Q.front().enemy_col)){
					next_enemy_row = Q.front().enemy_row-1;
					next_enemy_col = Q.front().enemy_col;
				}else{
					next_enemy_row = Q.front().enemy_row;
					next_enemy_col = Q.front().enemy_col;
				}
				break;
			}

			for(int i = 0; i < 5; i++){
				next_my_row = Q.front().my_row + diff_row[i];
				next_my_col = Q.front().my_col + diff_col[i];

				if(rangeCheck(next_my_row,next_my_col) == true && map[next_my_row][next_my_col] != '#' &&
						check[next_my_row][next_my_col][next_enemy_row][next_enemy_col][tmp] == false){
					check[next_my_row][next_my_col][next_enemy_row][next_enemy_col][tmp] = true;
					Info next;
					next.enemy_row = next_enemy_row;
					next.enemy_col = next_enemy_col;
					next.my_row = next_my_row;
					next.my_col = next_my_col;
					next.my_time = Q.front().my_time;
					Q.push(next);
				}else{
					if(check[Q.front().my_row][Q.front().my_col][next_enemy_row][next_enemy_col][tmp] == false){
						check[Q.front().my_row][Q.front().my_col][next_enemy_row][next_enemy_col][tmp] = true;
						Info next;
						next.enemy_row = next_enemy_row;
						next.enemy_col = next_enemy_col;
						next.my_row = Q.front().my_row;
						next.my_col = Q.front().my_col;
						next.my_time = Q.front().my_time;
						Q.push(next);
					}
				}
			}
			Q.pop();
		}

		if(!FLG){
			printf("impossible\n");
		}else{
			printf("%d %d %d\n",ans_time,ans_row,ans_col);
		}
	}

	return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 9188
final_rank: 13

code_snippet: #include <bits/stdc++.h>
using namespace std;

typedef long long ll;
#define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i))
#define each(itr,c) for(__typeof(c.begin()) itr=c.begin(); itr!=c.end(); ++itr)
#define all(x) (x).begin(),(x).end()
#define pb push_back
#define fi first
#define se second

struct Place{ int x,y; };
struct State
{
    Place h,g;
    int p;
};

const int INF=123456789;
int z[20][20][20][20][10];
inline void init()
{
    rep(a,20)rep(b,20)rep(c,20)rep(d,20)rep(e,10) z[a][b][c][d][e]=INF;
}

int dx[5]={1,-1,0,0,0}, dy[5]={0,0,1,-1,0};

int main()
{
    int h,w;
    while(cin >>h >>w,h)
    {
        vector<string> s(h);
        rep(i,h) cin >>s[i];

        string pattern;
        cin >>pattern;
        int P=pattern.size();
        vector<int> pat(P);
        rep(i,P)
        {
            if(pattern[i]=='6') pat[i]=0;
            else if(pattern[i]=='4') pat[i]=1;
            else if(pattern[i]=='2') pat[i]=2;
            else if(pattern[i]=='8') pat[i]=3;
            else if(pattern[i]=='5') pat[i]=4;
        }

        Place a,b;
        rep(i,h)rep(j,w)
        {
            if(s[i][j]=='A') a=Place{j,i};
            if(s[i][j]=='B') b=Place{j,i};
        }

        init();
        z[a.y][a.x][b.y][b.x][0]=0;
        queue<State> que;
        que.push(State{a,b,0});
        #define IN(x,y) (0<=x && x<w && 0<=y && y<h)
        while(!que.empty())
        {
            State now=que.front(); que.pop();
            a=now.h;
            b=now.g;
            int idx=now.p;
            int nowZ=z[a.y][a.x][b.y][b.x][idx];

            // ???????????????
            int nbx=b.x+dx[pat[idx]], nby=b.y+dy[pat[idx]];
            if(!IN(nbx,nby))
            {
                nbx=b.x;
                nby=b.y;
            }
            Place nb=Place{nbx,nby};
            int nidx=(idx+1)%P;

            // ????????????
            rep(i,5)
            {
                int nax=a.x+dx[i], nay=a.y+dy[i];
                if(IN(nax,nay) && s[nay][nax]!='#' && z[nay][nax][nby][nbx][nidx] > nowZ+1)
                {
                    z[nay][nax][nby][nbx][nidx] = nowZ+1;
                    Place na=Place{nax,nay};
                    que.push(State{na,nb,nidx});
                }
            }
        }

        int ans=INF,ax=-1,ay=-1;
        rep(i,h)rep(j,w)rep(k,P)
        {
            if(ans>z[i][j][i][j][k])
            {
                ans=z[i][j][i][j][k];
                ax=j;
                ay=i;
            }
        }

        if(ans==INF) printf("impossible\n");
        else printf("%d %d %d\n", ans,ay,ax);
    }
    return 0;
}
accuracy: 1
time_ms: 50
memory_kb: 9488
final_rank: 15

code_snippet: #include "bits/stdc++.h"
#include<unordered_map>
#include<unordered_set>
#pragma warning(disable:4996)
using namespace std;
using ld = long double;
template<class t>
using table = vector<vector<t>>;
const ld eps = 1e-9;

//// < "d:\d_download\visual studio 2015\projects\programing_contest_c++\debug\a.txt" > "d:\d_download\visual studio 2015\projects\programing_contest_c++\debug\b.txt"
  

const int dx[] = { -1,0,1,0,0 };
const int dy[] = { 0,1,0,-1,0 };

int memo[22][22][22][22][10];

struct aa{
	int mx;
	int my;
	int gx;
	int gy;
	int num;
	int time;
};

class Compare {
public:
	bool operator()(const aa&l, const aa&r) {
		return l.time> r.time;
	}
};	//aa?????????????????¶


pair<int, int>amove(const vector<vector<int>>&field, const int nx, const int ny,const int move,bool gh) {

	const int nexty = ny +dy[move];
	const int nextx =nx + dx[move];
	if (gh) {

		if (field[nexty][nextx]!=2)return make_pair(nextx, nexty);
		else return make_pair(nx, ny);
	}
	else {

		if (!field[nexty][nextx])return make_pair(nextx, nexty);
		else return make_pair(nx, ny);
	}
}
int main() {
	while (1) {
		int H, W; cin >> H >> W;
		if (!H)break;
		for (int i = 0; i < 22; ++i) {
			for (int j = 0; j < 22; ++j) {
				for (int k = 0; k < 22; ++k) {
					for (int l = 0; l < 22; ++l) {
						for (int m = 0; m < 10; ++m) {
							memo[i][j][k][l][m] = 1e8;
						}
					}
				}
			}
		}
		int mx, my, gx, gy;
		vector<vector<int>>field(H + 2, vector<int>(W + 2,2));
		for (int i = 0; i < H; ++i) {
			string st; cin >> st;
			for (int j = 0; j < W; ++j) {
				if (st[j] == 'A') {
					mx = j + 1; my = i + 1;
					field[i+1][j+1] = false;
				}
				else if (st[j] == 'B') {
					gx = j + 1; gy = i + 1;
					field[i + 1][j + 1] = false;

				}
				else if (st[j] == '#') {
					field[i + 1][j + 1] =true;

				}
				else {
					field[i + 1][j + 1] = false;

				}
			}
			
		}
		string pattern; cin >> pattern;
		vector<int>moves(pattern.size());
		for (int i = 0; i < pattern.size(); ++i) {
			if (pattern[i] == '8')moves[i] = 3;
			else if (pattern[i] == '6')moves[i] = 2;
			else if (pattern[i] == '4')moves[i] = 0;
			else if (pattern[i] == '2')moves[i] = 1;
			else moves[i] = 4;
		}
		memo[mx][my][gx][gy][0] = 0;
		priority_queue<aa, vector<aa>, Compare>que;
		que.push(aa{ mx,my,gx,gy,0,0 });
		int ans = -1;
		int ansx, ansy;
		while (!que.empty()) {
			aa atop(que.top());
			que.pop();
			if (atop.gx == atop.mx&&atop.gy == atop.my) {
				ans = atop.time;
				ansx = atop.gx;
				ansy = atop.gy;
				break;
			}
			auto gp(amove(field, atop.gx, atop.gy, moves[atop.num],true));
			const int nextgx = gp.first;
			const int nextgy = gp.second;
			const int nextnum = (atop.num + 1) % moves.size();
			for (int way = 0; way < 5; ++way) {
				auto amp(amove(field, atop.mx, atop.my, way,false));

				const int nextmx = amp.first;
				const int nextmy = amp.second;
				if (memo[nextmx][nextmy][nextgx][nextgy][nextnum]>atop.time + 1) {
					memo[nextmx][nextmy][nextgx][nextgy][nextnum] = atop.time + 1;
					que.push(aa{ nextmx,nextmy,nextgx,nextgy,nextnum,atop.time + 1 });

				}
			}
		}
		if (ans == -1)cout << "impossible" << endl;
		else {
			cout << ans<<" "<<ansy-1<<" "<<ansx -1<< endl;
		}
	}
	
	return 0;
}
accuracy: 1
time_ms: 60
memory_kb: 12300
final_rank: 17

code_snippet: #include <iostream>
#include <queue>
#include <cstring>
 
using namespace std;
 
#define MAX 20
#define INF 1e9
 
int H,W,ax,ay,bx,by;
char field[MAX][MAX];
string str;
const int dx[] = {-1,0,0,1,0};
const int dy[] = {0,-1,1,0,0};
 
struct State{
    int sx,sy,gx,gy;
    State(int sx,int sy,int gx,int gy) : sx(sx),sy(sy),gx(gx),gy(gy) {}
};
 
bool inField(int y,int x){
    return 0 <= y && y < H && 0 <= x && x < W;
}
 
int getDir(char ch){
    if(ch == '4') return 0;
    if(ch == '8') return 1;
    if(ch == '2') return 2;
    if(ch == '6') return 3;
    return 4;
}
 
void bfs(){
    int size = str.size();
    bool visited[MAX][MAX][MAX][MAX][MAX];
    memset(visited,0,sizeof(visited));
    visited[ay][ax][by][bx][0] = true;
    queue<State> Q;
    queue<int> Count;
    Q.push(State(ax,ay,bx,by));
    Count.push(0);
    while(!Q.empty()){
	State s = Q.front(); Q.pop();
	int cnt = Count.front(); Count.pop();
 
	if(s.sx == s.gx && s.sy == s.gy){
	    cout << cnt << " " << s.sy << " " << s.sx << endl;
	    return;
	}
 
	int dir = getDir(str[cnt%size]);
	int Gx = s.gx + dx[dir], Gy = s.gy + dy[dir];
	if(!inField(Gy,Gx)) Gx = s.gx, Gy = s.gy;
 
	for(int i = 0 ; i < 5 ; i++){
	    int nx = s.sx + dx[i], ny = s.sy + dy[i];
	    if(!inField(ny,nx)) continue;
	    if(field[ny][nx] == '#') continue;
	    if(visited[ny][nx][Gy][Gx][(cnt+1)%size]) continue;
	    visited[ny][nx][Gy][Gx][(cnt+1)%size] = true;
	    Q.push(State(nx,ny,Gx,Gy));
	    Count.push(cnt+1);
	}
    }
    cout << "impossible" << endl;
}
 
int main(){
    while(cin >> H >> W, (H|W)){
	for(int i = 0 ; i < H ; i++){
	    for(int j = 0 ; j < W ; j++){
		cin >> field[i][j];
		if(field[i][j] == 'A'){
		    ax = j, ay = i;
		}else if(field[i][j] == 'B'){
		    bx = j, by = i;
		}
	    }
	}
	cin >> str;
	bfs();
    }
    return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 6288
final_rank: 11

code_snippet: #include<iostream>
#include<queue>
using namespace std;
typedef pair<pair<int,int>,int> pa;
#define ff first.first
#define fs first.second

int h,w,sx,sy,gx,gy;
int dx[4]={1,0,-1,0};
int dy[4]={0,-1,0,1};
int co[21][21];
char ma[21][21];
bool visited[21][21];
string pat;
int m = 999999;

int main(){
    while(cin>>h>>w,h){
        for(int i=0;i<h;i++){
            for(int j=0;j<w;j++){
                co[i][j]=m;
                cin>>ma[i][j];
                if(ma[i][j]=='A')
                    sx=j,sy=i;
                else if(ma[i][j]=='B')
                    gx=j,gy=i;
            }
        }
        queue<pa>q;
        q.push(make_pair(make_pair(sx, sy), 0));
        while(q.size()){
            pa p = q.front();
            q.pop();
            if(co[p.fs][p.ff]!=m)
                continue;
            co[p.fs][p.ff]=p.second;
            for(int i=0;i<4;i++){
                int nx=p.ff+dx[i];
                int ny=p.fs+dy[i];
                if(nx>=0&&nx<w&&ny>=0&ny<h&&ma[ny][nx]!='#'&&co[ny][nx]==m)
                    q.push(make_pair(make_pair(nx, ny), p.second+1));
            }
        }
        cin>>pat;
        for(int j=0,go=0;;j++,go++){
            int i=j%pat.length();
            if(co[gy][gx]<=go){
                cout<<go<<" "<<gy<<" "<<gx<<endl;
                break;
            }
            if(go>100000){
                cout<<"impossible"<<endl;
                break;
            }
            if(pat[i]=='8')
                gy--;
            else if(pat[i]=='6')
                gx++;
            else if(pat[i]=='4')
                gx--;
            else if(pat[i]=='2')
                gy++;
            gy=max(0,min(h-1,gy));
            gx=max(0,min(w-1,gx));
        }
    }
}
accuracy: 1
time_ms: 20
memory_kb: 1228
final_rank: 6

code_snippet: #include<iostream>
#include<algorithm>
#include<climits>
#include<vector>
#include<queue>
#include<stack>
#include<cmath>
#include<string.h>

using namespace std;

int h,w,sx,sy,gx,gy;
int dx[4]={1,0,-1,0};
int dy[4]={0,-1,0,1};

char ma[21][21];
int co[21][21];
bool visited[21][21];

int main(){
    while(cin>>h>>w,h){
        for(int i=0;i<h;i++){
            for(int j=0;j<w;j++){
                co[i][j]=INT_MAX;
                cin>>ma[i][j];
                if(ma[i][j]=='A'){
                    sx=j,sy=i;
                } else if(ma[i][j]=='B'){
                    gx=j,gy=i;
                }
            }
        }
        queue<pair<pair<int,int>,int> >q;
        q.push(make_pair(make_pair(sx, sy), 0));
        while(q.size()){
           // cout<<q.size()<<endl;
            pair<pair<int,int>,int> p = q.front();
            q.pop();
            if(co[p.first.second][p.first.first]!=INT_MAX){
                continue;
            }
           // cout<<p.first.second<<" "<<p.first.first<<endl;
            co[p.first.second][p.first.first]=p.second;
            for(int i=0;i<4;i++){
                int nx=p.first.first+dx[i];
                int ny=p.first.second+dy[i];
                if(nx>=0&&nx<w&&ny>=0&ny<h&&ma[ny][nx]!='#'&&co[ny][nx]==INT_MAX){
                    q.push(make_pair(make_pair(nx, ny), p.second+1));
                }
            }
           // cout<<q.size()<<endl;
        }
        string pat;
        cin>>pat;
        int go=0;
        for(int j=0;;j++){
            int i=j%pat.length();
         //   cout<<gy<<" "<<gx<<" "<<co[gy][gx]<<" "<<INT_MAX<<endl;
            if(co[gy][gx]<=go){
                cout<<go<<" "<<gy<<" "<<gx<<endl;
                break;
            }
            if(go>100000){
                cout<<"impossible"<<endl;
                break;
            }
            if(pat[i]=='5'){
                
            } else if(pat[i]=='8'){
                gy--;
            } else if(pat[i]=='6'){
                gx++;
            } else if(pat[i]=='4'){
                gx--;
            } else if(pat[i]=='2'){
                gy++;
            }
            gy=max(0,gy);
            gy=min(h-1,gy);
            gx=max(0,gx);
            gx=min(w-1,gx);
            go++;
        }
    }
}
accuracy: 1
time_ms: 20
memory_kb: 1228
final_rank: 6

code_snippet: #include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> P;
typedef pair<P,P> Pi;
typedef pair<P,Pi> Pii;
int H,W;
char mas[22][22];
string pat;
int ax,ay,bx,by;
int dx[] = {0,1,-1,0,0};
int dy[] = {0,0,0,-1,1};

int solved(){
  bool used[10][20][20][20][20];
  memset(used,false,sizeof(used));
  queue<Pii> que;
  int len = pat.size();
  que.push(Pii(P(0,0),Pi(P(ax,ay),P(bx,by))));
  used[0][ax][ay][bx][by] = true;
  while(!que.empty()){
    Pii p = que.front(); que.pop();
    int cnt = p.first.first;
    int idx = p.first.second;
    int Ax = p.second.first.first;
    int Ay = p.second.first.second;
    int Bx = p.second.second.first;
    int By = p.second.second.second;
    if(Ax == Bx && Ay == By) {
      cout << cnt << " " << Ay << " " << Ax << endl;
      return 1;
    }
    int nBx = Bx;
    int nBy = By;
    if(pat[idx] == '8') nBy = max(0,nBy-1);
    else if(pat[idx] == '6') nBx = min(W-1,nBx+1);
    else if(pat[idx] == '4') nBx = max(0,nBx-1);
    else if(pat[idx] == '2') nBy = min(H-1,nBy+1);
    for(int i=0;i<5;i++){
      int nAx = Ax+dx[i];
      int nAy = Ay+dy[i];
      if(nAx >= W || nAx < 0) nAx = Ax;
      if(nAy >= H || nAy < 0) nAy = Ay;
      if(mas[nAy][nAx] != '#'){
	int next = (idx+1)%len;
	if(used[next][nAx][nAy][nBx][nBy] == false){
	  used[next][nAx][nAy][nBx][nBy] = true;
	  que.push(Pii(P(cnt+1,next),Pi(P(nAx,nAy),P(nBx,nBy))));
	}	
      }
    }
  }
  return 0;
}

int main(){
  while(1){
    cin >> H >> W;
    if(H == 0 && W == 0) break;
    for(int i=0;i<H;i++){
      for(int j=0;j<W;j++){
	cin >> mas[i][j];
	if(mas[i][j] == 'A'){
	  ax = j;
	  ay = i;
	}
	if(mas[i][j] == 'B'){
	  bx = j;
	  by = i;
	}
      }
    }
    cin >> pat;
    if(solved() == 0){
      cout << "impossible" << endl;
    }
  }
}
accuracy: 1
time_ms: 20
memory_kb: 2800
final_rank: 8

code_snippet: #include <algorithm>
#include <iostream>
#include <queue>
#define m make_pair
#define INF (1e9)
#define N 20
using namespace std;
typedef pair<int,int> P;
typedef pair<int,P> P1;
void bfs();
int h,w,sx,sy,gy,gx,p,d[N][N],anst,ansy,ansx;
string str[N],pat;

int main(){
  while(1){
    cin>>h>>w;
    if(!h&&!w) break;
    for(int i=0;i<h;i++) cin>>str[i];
    cin>>pat;
    for(int i=0;i<h;i++)
      for(int j=0;j<w;j++){
	if(str[i][j]=='A') sx=j,sy=i;
	if(str[i][j]=='B') gx=j,gy=i;
      }
    bfs();
    int len=pat.size(),t=0,eflag=0;
    p=0;
    while(1){
      int cy=gy,cx=gx;
      if(pat[p]=='8') gy--;
      if(pat[p]=='6') gx++;
      if(pat[p]=='4') gx--;
      if(pat[p]=='2') gy++;
      p++;
      t++;
      if(p==len) p=0;
      if(gy<0||h<=gy||gx<0||w<=gx) gy=cy,gx=cx;
      if(d[gy][gx]!=INF&&d[gy][gx]<=t){
	anst=max(d[gy][gx],t);
	ansy=gy;
	ansx=gx;
	break;
      }
      if(t==100000){
	eflag=1;
	break;
      }
    }
    if(!eflag) cout<<anst<<' '<<ansy<<' '<<ansx<<endl;
    else cout<<"impossible"<<endl;
  }
  return 0;
}

void bfs(){
  int dy[4]={-1,0,1,0};
  int dx[4]={0,1,0,-1};
  queue<P1> q;
  for(int i=0;i<N;i++)
    for(int j=0;j<N;j++) d[i][j]=INF;
  d[sy][sx]=0;
  q.push(m(0,m(sy,sx)));
  while(!q.empty()){
    P1 t=q.front(); q.pop();
    int c=t.first,uy=t.second.first,ux=t.second.second;
    for(int i=0;i<4;i++){
      int ny=uy+dy[i],nx=ux+dx[i];
      if(ny<0||h<=ny||nx<0||w<=nx) continue;
      if(str[ny][nx]=='#') continue;
      if(d[ny][nx]>c+1){
	d[ny][nx]=c+1;
	q.push(m(d[ny][nx],m(ny,nx)));
      }
    }
  }
}
accuracy: 1
time_ms: 10
memory_kb: 1228
final_rank: 1

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define F first
#define S second
#define INF 1<<29
typedef pair<int,int> P;
struct PP {
  P a,b;
  int kk;
};

int dx[5]={-1,0,1,0,0},dy[5]={0,1,0,-1,0};
bool check(int n,int m,int x,int y){return x>=0&&x<n&&y>=0&&y<m;}

int main() {
  int n,m;
  while(cin >> n >> m && n) {
    string s[n],t;
    for(int i=0; i<n; i++) cin >> s[i];
    cin >> t;
    for(int i=0; i<t.size(); i++) {
      if(t[i]=='5') t[i]='4';
      else if(t[i]=='8') t[i]='0';
      else if(t[i]=='6') t[i]='1';
      else if(t[i]=='2') t[i]='2';
      else t[i]='3';
    }
    P p1,p2;
    for(int i=0; i<n; i++) {
      for(int j=0; j<m; j++) {
        if(s[i][j]=='A') p1=P(i,j);
        if(s[i][j]=='B') p2=P(i,j);
      }
    }
    int d[n][m][n][m][t.size()];
    for(int i=0;i<n;i++)for(int i2=0;i2<m;i2++)for(int i3=0;i3<n;i3++)for(int i4=0;i4<m;i4++)for(int i5=0;i5<t.size();i5++)d[i][i2][i3][i4][i5]=INF;
    d[p1.F][p1.S][p2.F][p2.S][t.size()-1]=0;
    queue<PP> que;
    que.push((PP){p1,p2,t.size()-1});
    while(!que.empty()) {
      PP p=que.front();que.pop();
      int nx=p.a.F,ny=p.a.S,k=p.kk;
      P q=p.b;
      int cost=d[nx][ny][p.b.F][p.b.S][p.kk];
      if(p.a==p.b) {
        cout << cost << " " << nx << " " << ny << endl;
        goto end;
      }
      k=(k+1)%t.size();
      int r=t[k]-'0';
      q.F+=dx[r],q.S+=dy[r];
      if(!check(n,m,q.F,q.S)) q=p.b;
      for(int i=0; i<5; i++) {
        int x=nx+dx[i],y=ny+dy[i];
        if(!check(n,m,x,y)||s[x][y]=='#') continue;
        if(d[x][y][q.F][q.S][k]>cost+1) {
          d[x][y][q.F][q.S][k]=cost+1;
          que.push((PP){P(x,y),q,k});
        }
      }
    }
    cout << "impossible" << endl;
  end:;
  }
  return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 7492
final_rank: 12

code_snippet: #include<bits/stdc++.h>
using namespace std;
const int INF=1001001001;
typedef pair<int,int>P;
const int dx[]={-1,0,1,0,0};
const int dy[]={0,-1,0,1,0};
int H,W;
char fld[50][50];
int sy,sx,gy,gx;
int dist[50][50];
int ord[10],N;
bool ok(int y,int x){
    if(y<0||y>=H||x<0||x>=W)return false;
    return true;
}

void bfs(){
    for(int i=0;i<H;i++)for(int j=0;j<W;j++)dist[i][j]=INF;
    dist[sy][sx]=0;

    queue<P>que;que.push(P(sy,sx));

    while(que.size()){
        P p=que.front();que.pop();

        for(int i=0;i<4;i++){
            int ny=p.first+dy[i],nx=p.second+dx[i];
            if(!ok(ny,nx)||fld[ny][nx]=='#'||dist[ny][nx]!=INF)continue;
            dist[ny][nx]=dist[p.first][p.second]+1;
            que.push(P(ny,nx));
        }
    }
}

void solve(){
    for(int i=0;i<H;i++){
        cin>>fld[i];
        for(int j=0;j<W;j++){
            if(fld[i][j]=='A')sy=i,sx=j;
            if(fld[i][j]=='B')gy=i,gx=j;
        }
    }

    bfs();

    string str;cin>>str;
    N=str.size();
    for(int i=0;i<N;i++){
        switch(str[i]){
            case '5':ord[i]=4;break;
            case '8':ord[i]=1;break;
            case '4':ord[i]=0;break;
            case '2':ord[i]=3;break;
            case '6':ord[i]=2;break;
        }
    }

    for(int i=0;i<100000;i++){
        int ny=gy+dy[ord[i%N]],nx=gx+dx[ord[i%N]];
        if(ok(ny,nx)){
            gy=ny;gx=nx;
        }

        if(dist[gy][gx]<=i+1){
            cout<<i+1<<" "<<gy<<" "<<gx<<endl;
            return;
        }
    }

    cout<<"impossible"<<endl;
}

int main(){
    while(cin>>H>>W,H||W)solve();
    return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 1232
final_rank: 2

code_snippet: #include <cstdlib>
#include <cmath>
#include <climits>
#include <cfloat>
#include <map>
#include <set>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <complex>
#include <stack>
#include <queue>
#include <cstdio>
#include <cstring>
#include <iterator>
#include <bitset>
#include <unordered_set>
#include <unordered_map>
#include <fstream>
#include <iomanip>
//#include <utility>
//#include <memory>
//#include <functional>
//#include <deque>
//#include <cctype>
//#include <ctime>
//#include <numeric>
//#include <list>
//#include <iomanip>

//#if __cplusplus >= 201103L
//#include <array>
//#include <tuple>
//#include <initializer_list>
//#include <forward_list>
//
//#define cauto const auto&
//#else

//#endif

using namespace std;


typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;

typedef vector<int> vint;
typedef vector<vector<int> > vvint;
typedef vector<long long> vll, vLL;
typedef vector<vector<long long> > vvll, vvLL;

#define VV(T) vector<vector< T > >

template <class T>
void initvv(vector<vector<T> > &v, int a, int b, const T &t = T()){
    v.assign(a, vector<T>(b, t));
}

template <class F, class T>
void convert(const F &f, T &t){
    stringstream ss;
    ss << f;
    ss >> t;
}

#undef _P
#define _P(...) (void)printf(__VA_ARGS__)
#define reep(i,a,b) for(int i=(a);i<(b);++i)
#define rep(i,n) reep((i),0,(n))
#define ALL(v) (v).begin(),(v).end()
#define PB push_back
#define F first
#define S second
#define mkp make_pair
#define RALL(v) (v).rbegin(),(v).rend()
#define DEBUG
#ifdef DEBUG
#define dump(x)  cout << #x << " = " << (x) << endl;
#define debug(x) cout << #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl;
#else
#define dump(x) 
#define debug(x) 
#endif
#define LDcout(x,n) fixed<<setprecision(n)<<x

#define MOD 1000000007LL
#define EPS 1e-8
static const int INF=1<<24;
int h,w;
int dd[]={0,1,0,-1,0};
bool check(int a,int b){
	if(0<=a&&a<h&&0<=b&&b<w) return true;
	return false;
}
void bfs(pii p,int x,vector<string> &v,vvint &vv){
	if(vv[p.F][p.S]<=x) return;
	vv[p.F][p.S]=x;
	rep(i,4){
		pii ne=pii(p.F+dd[i],p.S+dd[i+1]);
		if(!check(ne.F,ne.S)||v[ne.F][ne.S]=='#') continue;
		bfs(ne,x+1,v,vv);
	}
}
void mainmain(){
	vector<pii> vec(10);
	vec[2]=pii(1,0);
	vec[4]=pii(0,-1);
	vec[5]=pii(0,0);
	vec[6]=pii(0,1);
	vec[8]=pii(-1,0);
	while(cin>>h>>w,h||w){
		vector<string> v(h);
		rep(i,h) cin>>v[i];
		string s;
		cin>>s;
		vvint vv;
		initvv(vv,h,w,-1);
		pii A,B;
		rep(i,h){
			rep(j,w){
				if(v[i][j]=='A'){
					A=pii(i,j);
					v[i][j]='.';
				}
				if(v[i][j]=='B'){
					B=pii(i,j);
					v[i][j]='.';
				}
			}
		}
		// bfs(A,0,v,vv);
		queue<pair<pii,int>> q;
		q.push(mkp(A,0));
		vv[A.F][A.S]=0;
		while(q.size()){
			auto top=q.front();
			q.pop();
			rep(i,4){
				pii ne(top.F.F+dd[i],top.F.S+dd[i+1]);
				if(!check(ne.F,ne.S)||v[ne.F][ne.S]=='#'||vv[ne.F][ne.S]>=0) continue;
				vv[ne.F][ne.S]=top.S+1;
				q.push(mkp(ne,top.S+1));
			}
		}
		int ans=-1;
		pii pos;
		rep(i,h){
			rep(j,w){
				// printf("%2d ",vv[i][j]);
				if(vv[i][j]==-1) vv[i][j]=INF;
			}
			// cout<<endl;
		}
		rep(i,1e5){
			// cout<<i<<" "<<B.F<<" "<<B.S<<endl;
			if(vv[B.F][B.S]<=i){
				ans=i;
				pos=B;
				break;
			}
			int t=s[i%s.size()]-'0';
			pii ne=pii(B.F+vec[t].F,B.S+vec[t].S);
			if(check(ne.F,ne.S)){
				B=ne;
			}
		}
		if(ans==-1){
			cout<<"impossible"<<endl;
		}
		else{
			cout<<ans<<" "<<pos.F<<" "<<pos.S<<endl;
		}
		// return;
	}
}


signed main() {
	// ios_base::sync_with_stdio(false);
  	cout<<fixed<<setprecision(20);
    mainmain();
}
accuracy: 1
time_ms: 10
memory_kb: 1236
final_rank: 3

code_snippet: #include <iostream>
#include <complex>
#include <sstream>
#include <string>
#include <algorithm>
#include <deque>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <vector>
#include <set>
#include <limits>
#include <cstdio>
#include <cctype>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <ctime>
using namespace std;
#define REP(i, j) for(int i = 0; i < (int)(j); ++i)
#define FOR(i, j, k) for(int i = (int)(j); i < (int)(k); ++i)
#define SORT(v) sort((v).begin(), (v).end())
#define REVERSE(v) reverse((v).begin(), (v).end())
typedef complex<double> P;
const int INF = 1e5;

int H, W;
int my[] = {0, 0, 1, -1};
int mx[] = {1, -1, 0, 0};

void dfsA(int t, int y, int x, vector<string> &v, vector< vector<int> > &cnt){
  REP(i, 4){
    int ny = y + my[i], nx = x + mx[i];
    if(ny >= 0 && nx >= 0 && ny < H && nx < W && v[ny][nx] != '#' && cnt[ny][nx] > t + 1){
      cnt[ny][nx] = t + 1;
      dfsA(t + 1, ny, nx, v, cnt);
    }
  }
}

int main() {
  while(cin >>H >>W && H){
    vector<string> v(H); REP(i, H) cin >>v[i];
    vector< vector<int> > cntA(H, vector<int>(W, INF));
    REP(i, H) REP(j, W) if(v[i][j] == 'A') { cntA[i][j] = 0; dfsA(0, i, j, v, cntA); }
    string pattern; cin >>pattern;
    int y, x, ay, ax, ans = INF, pl = pattern.length();
    REP(i, H) REP(j, W) if(v[i][j] == 'B') { y = i; x = j; }
    REP(i, INF){
      if(cntA[y][x] <= i) { ans = i; ay = y; ax = x; break; }
      //cout <<y <<", " <<x <<", " <<cntA[y][x] <<", " <<i <<endl;
      if(pattern[i % pl] == '8') { y = max(0, y - 1); }
      else if(pattern[i % pl] == '6') { x = min(W - 1, x + 1); }
      else if(pattern[i % pl] == '4') { x = max(0, x - 1); }
      else if(pattern[i % pl] == '2') { y = min(H - 1, y + 1); }
    }
    if(ans == INF) cout <<"impossible" <<endl;
    else cout <<ans <<" " <<ay <<" " <<ax <<endl;
  }
  return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 1264
final_rank: 4

code_snippet: #include <bits/stdc++.h>
using namespace std;
const int dx[] = {-1, 0, 1, 0, 0};
const int dy[] = {0, -1, 0, 1, 0};

struct STATE { int ax, ay, bx, by, d; };

char grid[32][32];
bool done[32][32][32][32][16];

int main()
{
	int h, w;
	while (scanf("%d %d", &h, &w), h + w){
		memset(grid, '*', sizeof(grid));
		memset(done, false, sizeof(done));
		STATE s = {0, 0, 0, 0, 0};
		
		for (int i = 1; i <= h; i++){
			for (int j = 1; j <= w; j++){
				scanf(" %c", &grid[i][j]);
				if (grid[i][j] == 'A'){
					s.ax = i;
					s.ay = j;
					grid[i][j] = '.';
				}
				else if (grid[i][j] == 'B'){
					s.bx = i;
					s.by = j;
					grid[i][j] = '.';
				}
			}
		}
		
		/*
		for (int i = 1; i <= h; i++){
			for (int j = 1; j <= w; j++){
				printf("%c", grid[i][j]);
			}
			cout << endl;
		}
		*/
		
		string pa;
		cin >> pa;
		for (int i = 0; i < pa.size(); i++){
			if (pa[i] == '5') pa[i] = 4;
			else if (pa[i] == '8') pa[i] = 0;
			else if (pa[i] == '6') pa[i] = 3;
			else if (pa[i] == '4') pa[i] = 1;
			else if (pa[i] == '2') pa[i] = 2;
		}
		
		STATE res = {0, 0, 0, 0, -1};
		queue<STATE> que;
		for (que.push(s); que.size(); que.pop()){
			STATE st = que.front();
			
			//printf("%d %d %d %d\n", st.ax, st.ay, st.bx, st.by);
			
			if (done[st.ax][st.ay][st.bx][st.by][st.d % pa.size()]){
				continue;
			}
			done[st.ax][st.ay][st.bx][st.by][st.d % pa.size()] = true;
			if (st.ax == st.bx && st.ay == st.by){
				res = st;
				break;
			}
			
			
			int tbx = st.bx + dx[pa[st.d % pa.size()]];
			int tby = st.by + dy[pa[st.d % pa.size()]];
			if (grid[tbx][tby] == '*'){
				tbx = st.bx;
				tby = st.by;
			}
			for (int dir = 0; dir < 5; dir++){
				int tax = st.ax + dx[dir];
				int tay = st.ay + dy[dir];
				if (grid[tax][tay] != '.') continue;
				que.push({tax, tay, tbx, tby, st.d + 1});
			}
		}
		
		if (res.d == -1) cout << "impossible" << endl;
		else cout << res.d << " " << res.ax - 1 << " " << res.ay - 1 << endl;
	}
	
	return 0;
}
accuracy: 1
time_ms: 70
memory_kb: 17680
final_rank: 19

code_snippet: #define _USE_MATH_DEFINES
#define INF 0x3f3f3f3f
#include <iostream>
#include <sstream>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <limits>
#include <map>
#include <string>
#include <cstring>
#include <set>
#include <deque>
#include <bitset>
#include <list>
 
using namespace std;
 
typedef long long ll;
typedef pair <int,int> P;
 
static const double EPS = 1e-8;

static const int tx[] = {0,1,0,-1};
static const int ty[] = {-1,0,1,0};

int H,W;
char stage[20][20];
string ghost;
bool visited[20][20][20][20][10];
int gTime = 0;
int rx,ry;

class State {
public:
  int _sx,_sy,_gx,_gy,_time;
  State(int sx,int sy,int gx,int gy,int time) : 
    _sx(sx),_sy(sy),_gx(gx),_gy(gy),_time(time) {}
  bool operator<(const State &s) const {
    return _time < s._time;
  }
  bool operator>(const State &s) const {
    return _time > s._time;
  }
};

void bfs(int sx,int sy,int gx,int gy){
  State init(sx,sy,gx,gy,0);
  
  priority_queue<State,vector<State>,greater<State> > que;
  que.push(init);

  while(!que.empty()){
    State s = que.top();
    que.pop();

    int pattern_i = s._time % ghost.size();
    if(ghost[pattern_i] == '5'){
      //nothing to do
    }
    else if(ghost[pattern_i] == '8' && s._gy - 1 >= 0){
      s._gy--;
    }
    else if(ghost[pattern_i] == '6' && s._gx + 1 < W){
      s._gx++;
    }
    else if(ghost[pattern_i] == '4' && s._gx - 1 >= 0){
      s._gx--;
    }
    else if(ghost[pattern_i] == '2' && s._gy + 1 < H){
      s._gy++;
    }

    if(!visited[s._sx][s._sy][s._gx][s._gy][pattern_i]){
      visited[s._sx][s._sy][s._gx][s._gy][pattern_i] = true;
      if(s._sx == s._gx && s._sy == s._gy && gTime > s._time){
        gTime = s._time;
        rx = s._gx;
        ry = s._gy;
        return;
      }
      que.push(State(sx,sy,s._gx,s._gy,s._time+1));
    }
    for(int i = 0; i < 4; i++){
      int dx = tx[i] + s._sx;
      int dy = ty[i] + s._sy;
      if(dx < 0 || dx >= W || dy < 0 || dy >= H) continue;
         if(stage[dy][dx] == '#') continue;
         if(visited[dx][dy][s._gx][s._gy][pattern_i]) continue;
         
         visited[dx][dy][s._gx][s._gy][pattern_i] = true;
         if(dx == s._gx && dy == s._gy && gTime > s._time){
           gTime = s._time;
           rx = s._gx;
           ry = s._gy;
           return;
         }
         que.push(State(dx,dy,s._gx,s._gy,s._time+1));
    }
  }
}

int main(){
  while(~scanf("%d %d",&H,&W)){
    if(H == 0 && W == 0) break;

    int sx,sy,gx,gy;
    memset(visited,false,sizeof(visited));
    gTime = INF;

    for(int y = 0; y < H; y++){
      char line[32];
      scanf("%s",line);
      for(int x = 0; x < W; x++){
        stage[y][x] = line[x];
        if(stage[y][x] == 'A'){
          sx = x;
          sy = y;
        }
        if(stage[y][x] == 'B'){
          gx = x;
          gy = y;
        }
      }
    }
    cin >> ghost;
    rx = -1;
    ry = -1;
    bfs(sx,sy,gx,gy);
    
    if(gTime == INF){
      printf("impossible\n");
    }
    else{
      printf("%d %d %d\n",gTime + 1,ry,rx);
    }
  }
}
accuracy: 1
time_ms: 20
memory_kb: 2832
final_rank: 9

code_snippet: #include <iostream>
#include <sstream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <cstring>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <bitset>
#include <numeric>
#include <utility>
#include <iomanip>
#include <algorithm>
#include <functional>
using namespace std;

typedef long long ll;
typedef vector<int> vint;
typedef vector<long long> vll;
typedef pair<int,int> pint;
typedef pair<long long, long long> pll;

#define MP make_pair
template<class T1, class T2> ostream& operator << (ostream &s, pair<T1,T2> P) 
{ return s << P.first << " " << P.second; }

int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};

int n, m;
char fi[25][25];
string pat;

int dist[25][25][25][25][11];

pair<int,pint> solve() {
    pint s, t;
    for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) {
        cin >> fi[i][j];
        if (fi[i][j] == 'A') s = pint(i,j);
        if (fi[i][j] == 'B') t = pint(i,j);
    }
    cin >> pat;
    memset(dist, -1, sizeof(dist));
    dist[s.first][s.second][t.first][t.second][0] = 0;
    queue< pair<pair<pint,pint>,int> > que;
    que.push( MP(MP(s,t),0) );
    while (!que.empty()) {
        pint girl = que.front().first.first;
        pint goast = que.front().first.second;
        int p = que.front().second;
        //cout << girl << ", " << goast << " : " << dist[girl.first][girl.second][goast.first][goast.second] << endl;
        que.pop();
        if (girl == goast) { 
            return MP(dist[girl.first][girl.second][goast.first][goast.second][p], girl); 
        }
        
        pint ngoast = goast;
        char c = pat[p];
        if (c == '8') ngoast = pint(goast.first-1, goast.second);
        if (c == '6') ngoast = pint(goast.first, goast.second+1);
        if (c == '4') ngoast = pint(goast.first, goast.second-1);
        if (c == '2') ngoast = pint(goast.first+1, goast.second);
        if (ngoast.first < 0 || ngoast.first >= n || ngoast.second < 0 || ngoast.second >= m) ngoast = goast;
        int np = (p+1)%pat.size();
        
        for (int i = 0; i < 5; ++i) {
            pint ngirl = girl;
            if (i < 4) ngirl = pint( girl.first + dx[i], girl.second + dy[i] );
            if (ngirl.first < 0 || ngirl.first >= n || ngirl.second < 0 || ngirl.second >= m) continue;
            if (fi[ngirl.first][ngirl.second] == '#') continue;
            if ( dist[ngirl.first][ngirl.second][ngoast.first][ngoast.second][np] == -1 ) {
                dist[ngirl.first][ngirl.second][ngoast.first][ngoast.second][np] 
                = dist[girl.first][girl.second][goast.first][goast.second][p] + 1;
                que.push( MP(MP(ngirl, ngoast),np) );
            }
        }
    }
    return MP(-1,pint(-1,-1));
}

int main() {
    while (cin >> n >> m) {
        if (n == 0) break;
        pair<int,pint> res = solve();
        if (res.first == -1) puts("impossible");
        else cout << res << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 60
memory_kb: 18020
final_rank: 18

code_snippet: #include <stdio.h>
#include <cctype>
#include <limits.h>
#include <math.h>
#include <complex>
#include <bitset>
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <cstring>
#include <string>
#include <sstream>
#include <algorithm>
#include <iomanip>
#include <iostream>

#define VARIABLE(x) cerr << #x << "=" << x << endl
#define BINARY(x) static_cast<bitset<16> >(x);
#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define REP(i,m,n) for (int i=m;i<(int)(n);i++)
#define if_range(x, y, w, h) if (0<=(int)(x) && (int)(x)<(int)(w) && 0<=(int)(y) && (int)(y)<(int)(h))

const int INF = 1000000000;
const double EPS = 1e-8;
const double PI = 3.14159;
//int dx[4]={-1, 0, 1, 0}, dy[4]={0, -1, 0, 1};
using namespace std;
//typedef pair<int, int> P;

/** Problem1046 : Ghost Buster! **/
int dx[]={-1, 0, 1, 0, 0}, dy[]={0, -1, 0, 1, 0};

int W, H;
string s;

struct P {
	int x, y;
	P(){}
	P(int _x, int _y) : x(_x), y(_y) {}
};

struct S {
	P p;
	int time;
	S(){}
	S(P _p, int _time) : p(_p), time(_time) {}
};

typedef pair<S, S> SS;

int main()
{
	
	while (cin>>H>>W, W||H) {
		char field[20][20];
		
		S A, B;
		
		rep(i, H) rep(j, W) {
			cin>>field[i][j];
			if (field[i][j] == 'A')
				A = S(P(j, i), 0);
			else if (field[i][j] == 'B')
				B = S(P(j, i), 0);
		}
		cin>>s;
		int N = (int)s.size();
		
		queue<SS> Q;
		bool vis[H][W][H][W][10];
		memset(vis, 0, sizeof(vis));
		
		Q.push(SS(A, B));
		vis[A.p.y][A.p.x][B.p.y][B.p.x][0] = true;
		
		while (Q.size()) {
			SS ss = Q.front(); Q.pop();
			S a = ss.first, b = ss.second;

			//cerr << "(" << a.p.x << ", " << a.p.y << ")" << " ";
			//cerr << "(" << b.p.x << ", " << b.p.y << ")" << " " << a.time << endl;
			
			if (a.p.x == b.p.x && a.p.y == b.p.y) {
				cout << a.time << " " << a.p.y << " " << a.p.x << endl;
				goto end;
			}
						
			// Move Ghost
			if (s[b.time%N] == '8' && b.p.y>0)
				b.p.y--;
			else if (s[b.time%N] == '6' && b.p.x<W-1)
				b.p.x++;
			else if (s[b.time%N] == '4' && b.p.x>0)
				b.p.x--;
			else if (s[b.time%N] == '2' && b.p.y<H-1)
				b.p.y++;
			b.time++;
			
			// Move Girl
			a.time++;
			rep(i, 5) {
				int nx = a.p.x + dx[i], ny = a.p.y + dy[i];
				if_range(nx, ny, W, H) {
					if (!vis[ny][nx][b.p.y][b.p.x][a.time%N] && field[ny][nx] != '#') {
						Q.push(SS(S(P(nx, ny), a.time), b));
						vis[ny][nx][b.p.y][b.p.x][a.time%N] = true;
					}
				}
			}
			
			if (!vis[a.p.y][a.p.x][b.p.y][b.p.x][b.time%N]) {
				Q.push(SS(a, b));
				vis[a.p.y][a.p.x][b.p.y][b.p.x][b.time%N] = true;
			}
		}
		cout << "impossible" << endl;
	end:;
	}
}
accuracy: 1
time_ms: 10
memory_kb: 2804
final_rank: 5

code_snippet: #include <iostream>
#include <queue>
#include <cstring>

using namespace std;

#define MAX 20
#define INF 1e9

int H,W,ax,ay,bx,by;
char field[MAX][MAX];
string str;
const int dx[] = {-1,0,0,1,0};
const int dy[] = {0,-1,1,0,0};

struct State{
  int sx,sy,gx,gy;
  State(int sx,int sy,int gx,int gy) : sx(sx),sy(sy),gx(gx),gy(gy) {}
};

bool inField(int y,int x){
  return 0 <= y && y < H && 0 <= x && x < W;
}

int getDir(char ch){
  if(ch == '4') return 0;
  if(ch == '8') return 1;
  if(ch == '2') return 2;
  if(ch == '6') return 3;
  return 4;
}

void bfs(){
  int size = str.size();
  bool visited[MAX][MAX][MAX][MAX][MAX];
  memset(visited,0,sizeof(visited));
  visited[ay][ax][by][bx][0] = true;
  queue<State> Q;
  queue<int> Count;
  Q.push(State(ax,ay,bx,by));
  Count.push(0);
  while(!Q.empty()){
    State s = Q.front(); Q.pop();
    int cnt = Count.front(); Count.pop();

    if(s.sx == s.gx && s.sy == s.gy){
      cout << cnt << " " << s.sy << " " << s.sx << endl;
      return;
    }

    int dir = getDir(str[cnt%size]);
    int Gx = s.gx + dx[dir], Gy = s.gy + dy[dir];
    if(!inField(Gy,Gx)) Gx = s.gx, Gy = s.gy;

    for(int i = 0 ; i < 5 ; i++){
      int nx = s.sx + dx[i], ny = s.sy + dy[i];
      if(!inField(ny,nx)) continue;
      if(field[ny][nx] == '#') continue;
      if(visited[ny][nx][Gy][Gx][(cnt+1)%size]) continue;
      visited[ny][nx][Gy][Gx][(cnt+1)%size] = true;
      Q.push(State(nx,ny,Gx,Gy));
      Count.push(cnt+1);
    }
  }
  cout << "impossible" << endl;
}

int main(){
  while(cin >> H >> W, (H|W)){
    for(int i = 0 ; i < H ; i++){
      for(int j = 0 ; j < W ; j++){
        cin >> field[i][j];
        if(field[i][j] == 'A'){
          ax = j, ay = i;
        }else if(field[i][j] == 'B'){
          bx = j, by = i;
        }
      }
    }
    cin >> str;
    bfs();
  }

  return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 4368
final_rank: 10

code_snippet: #include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <algorithm>

using namespace std;

#define rep(i,j) REP((i), 0, (j))
#define REP(i,j,k) for(int i=(j);(i)<(k);++i)
#define BW(a,x,b) ((a)<=(x)&&(x)<=(b))
#define MP make_pair
#define PB push_back
#define F first
#define S second
#define AY second.first.first
#define AX second.first.second
#define BY second.second.first
#define BX second.second.second
#define INF 1 << 30
#define EPS 1e-10

typedef pair<int, int> P;
typedef pair<int, P> pii;
typedef pair<P, P>pipi;
typedef vector<int> vi;
typedef queue<int> qi;
typedef long long ll;

int dy[] = {0, -1,0,1,0}, dx[] = {0, 0,-1,0,1};
int gdy[] = {0, 0, 1, 0, 0, 0, 0, 0, -1}, gdx[] = {0, 0, 0, 0, -1, 0, 1, 0, 0};
int H, W;
char field[32][32], pattern[16];

P nexta(int y, int x, int d){
  int ny = y+dy[d], nx = x+dx[d];
  ny = max(0, min(H-1, ny));
  nx = max(0, min(W-1, nx));
  if(field[ny][nx] == '#'){
    ny = y;
    nx = x;
  }
  return MP(ny, nx);
}

P nextb(int y, int x, int c){
  int L = strlen(pattern);
  int ny = y+gdy[pattern[c%L]-'0'], nx = x+gdx[pattern[c%L]-'0'];
  ny = max(0, min(H-1, ny));
  nx = max(0, min(W-1, nx));
  return MP(ny, nx);
}

int main(){
  while(scanf("%d%d", &H, &W) && H+W){
    rep(i, H) scanf("%s", field[i]);
    scanf("%s", pattern);
    int ay, ax, by, bx;
    rep(i, H) rep(j, W){
      if(field[i][j] == 'A'){ ay = i; ax = j;}
      else if(field[i][j] == 'B'){ by = i; bx = j;}
    }

    queue<pair<int, pipi> >q;
    map<pair<pipi, int>, int>m;
    q.push(MP(0, MP(MP(ay, ax), MP( by, bx))));
    m[MP(MP(MP(ay, ax), MP(by, bx)), -1)] = 1;

    while(!q.empty()){
      pair<int, pipi> now = q.front(); q.pop();
      if(now.AY == now.BY && now.AX == now.BX){
	printf("%d %d %d\n", now.F, now.AY, now.AX);
	goto e;
      }
      //      printf("%d %d %d %d %d\n", now.F, now.AY, now.AX, now.BY, now.BX);
      rep(d, 5){
	P na = nexta(now.AY, now.AX, d);
	P nb = nextb(now.BY, now.BX, now.F);
	//	int any = now.AY+dy[d], anx = now.AX+dx[d];
	//	int bny = now.BY+gdy[pattern[(now.F%strlen(pattern))]-'0'], bnx = now.BX+gdx[pattern[(now.F%strlen(pattern))]-'0'];
	//	printf("%d %d %d %d\n", any, anx, bny, bnx);
	//	if(any < 0 || any >= H || anx < 0 || anx >= W || bny < 0 || bny >= H || bnx < 0 || bnx >= W ||
	//	   field[any][anx] == '#' || m.count(MP(MP(any, anx), MP(bny, bnx)))) continue;
	if(m.count(MP(MP(na, nb), (now.F%strlen(pattern))))) continue;

	m[MP(MP(na, nb), now.F%strlen(pattern))] = 1;
	q.push(MP(now.F+1, MP(na, nb)));
      }
    }
    puts("impossible");
  e:;
  }
  return 0;
}
accuracy: 1
time_ms: 110
memory_kb: 3332
final_rank: 16