Problem:
Problem H:
Queen's Case
A small country called Maltius was governed by a queen. The queen was known as an oppressive ruler.
People in the country suffered from heavy taxes and forced labor. So some young people decided to form
a revolutionary army and fight against the queen. Now, they besieged the palace and have just rushed into
the entrance.
Your task is to write a program to determine whether the queen can escape or will be caught by the army.
Here is detailed description.
The palace can be considered as grid squares.
The queen and the army move alternately. The queen moves first.
At each of their turns, they either move to an adjacent cell or stay at the same cell.
Each of them must follow the optimal strategy.
If the queen and the army are at the same cell, the queen will be caught by the army immediately.
If the queen is at any of exit cells alone after the army’s turn, the queen can escape from the army.
There may be cases in which the queen cannot escape but won’t be caught by the army forever,
      under their optimal strategies.
Input
The input consists of multiple datasets. Each dataset describes a map of the palace. The first line of the input contains two integers
W
(1 ≤
W
≤ 30) and
H
(1 ≤
H
≤ 30), which indicate the width and height of the palace. The following
H
lines, each of which contains
W
characters, denote the map of the palace. "
Q
" indicates the queen, "
A
" the army,"
E
" an exit,"
#
" a wall and "
.
" a floor.
The map contains exactly one "
Q
", exactly one "
A
" and at least one "
E
". You can assume both the queen and the army can reach all the exits.
The last dataset is followed by a line containing two zeros. This line is not a part of any dataset and should not be processed.
Output
For each dataset, output "
Queen can escape.
", "
Army can catch Queen.
" or "
Queen can not escape and Army can not catch Queen.
" in a line.
Sample Input
2 2
QE
EA
3 1
QAE
3 1
AQE
5 5
..E..
.###.
A###Q
.###.
..E..
5 1
A.E.Q
5 5
A....
####.
..E..
.####
....Q
0 0
Output for the Sample Input
Queen can not escape and Army can not catch Queen.
Army can catch Queen.
Queen can escape.
Queen can not escape and Army can not catch Queen.
Army can catch Queen.
Army can catch Queen.
Hint
On the first sample input, the queen can move to exit cells, but either way the queen will be caught at the
next army’s turn. So the optimal strategy for the queen is staying at the same cell. Then the army can
move to exit cells as well, but again either way the army will miss the queen from the other exit. So the
optimal strategy for the army is also staying at the same cell. Thus the queen cannot escape but won’t be
caught.

Submitted solutions:

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, s, t) for (int i = (int)(s); i < (int)(t); ++i)
#define revrep(i, t, s) for (int i = (int)(t)-1; i >= (int)(s); --i)
#define all(x) begin(x), end(x)
template <typename T> bool chmax(T& a, const T& b) { return a < b ? (a = b, 1) : 0; }
template <typename T> bool chmin(T& a, const T& b) { return a > b ? (a = b, 1) : 0; }

int state[30][30][30][30][2];  // 0: queen, 1: army, -1: draw

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout << fixed << setprecision(15);

    const vector<int> di={-1,0,1,0,0};
    const vector<int> dj={0,1,0,-1,0};

    while(true){
        int w,h;
        cin>>w>>h;
        if (w==0) break;
        vector<string> grid(h);
        for(auto&s:grid)cin>>s;
        memset(state, -1, sizeof(state));

        stack<tuple<int,int,int,int,int>> st;

        auto get_neighbor = [&](int i, int j) {
            vector<pair<int,int>> res;
            rep(k,0,5){
                int ni = i+di[k], nj = j+dj[k];
                if (0 <= ni && ni < h && 0 <= nj && nj < w && grid[ni][nj] != '#') {
                    res.push_back({ni,nj});
                }
            }
            return res;
        };

        auto add_neighbor = [&](int i1, int j1, int i2, int j2, int turn) {
            if (turn == 0) {
                for (auto [ni2, nj2] : get_neighbor(i2, j2)) {
                    if (state[i1][j1][ni2][nj2][turn ^ 1] == -1) {
                        st.push({i1, j1, ni2, nj2, 1});
                    }
                }
            } else {
                for (auto [ni1, nj1] : get_neighbor(i1, j1)) {
                    if (state[ni1][nj1][i2][j2][turn ^ 1] == -1) {
                        st.push({ni1, nj1, i2, j2, 0});
                    }
                }
            }
        };

        rep(i1,0,h)rep(j1,0,w){
            if (grid[i1][j1] == '#') continue;
            rep(i2,0,h)rep(j2,0,w){
                if (grid[i2][j2] == '#') continue;
                // turn 0
                if (i1 == i2 && j1 == j2) {
                    state[i1][j1][i2][j2][0] = 1;
                    add_neighbor(i1, j1, i2, j2, 0);
                } else if (grid[i1][j1] == 'E') {
                    state[i1][j1][i2][j2][0] = 0;
                    add_neighbor(i1, j1, i2, j2, 0);
                }

                // turn 1
                if (i1 == i2 && j1 == j2) {
                    state[i1][j1][i2][j2][1] = 1;
                    add_neighbor(i1, j1, i2, j2, 1);
                }
            }
        }

        while (!st.empty()) {
            auto [i1, j1, i2, j2, turn] = st.top();
            st.pop();
            if (state[i1][j1][i2][j2][turn] != -1) continue;

            if (turn == 0) {
                // find at least one neighbor with state 0
                bool undecided = false;
                bool win = false;
                for (auto [ni1, nj1] : get_neighbor(i1, j1)) {
                    if (state[ni1][nj1][i2][j2][1] == -1) {
                        undecided = true;
                    } else if (state[ni1][nj1][i2][j2][1] == 0) {
                        win = true;
                        break;
                    }
                }
                if (win) {
                    state[i1][j1][i2][j2][0] = 0;
                    add_neighbor(i1, j1, i2, j2, 0);
                } else if (!undecided) {
                    state[i1][j1][i2][j2][0] = 1;
                    add_neighbor(i1, j1, i2, j2, 0);
                }
            } else {
                // find at least one neighbor with state 1
                bool undecided = false;
                bool win = false;
                for (auto [ni2, nj2] : get_neighbor(i2, j2)) {
                    if (state[i1][j1][ni2][nj2][0] == -1) {
                        undecided = true;
                    } else if (state[i1][j1][ni2][nj2][0] == 1) {
                        win = true;
                        break;
                    }
                }
                if (win) {
                    state[i1][j1][i2][j2][1] = 1;
                    add_neighbor(i1, j1, i2, j2, 1);
                } else if (!undecided) {
                    state[i1][j1][i2][j2][1] = 0;
                    add_neighbor(i1, j1, i2, j2, 1);
                }
            }
        }

        int si1, sj1, si2, sj2;
        rep(i,0,h) rep(j,0,w) {
            if (grid[i][j] == 'Q') si1 = i, sj1 = j;
            if (grid[i][j] == 'A') si2 = i, sj2 = j;
        }
        if (state[si1][sj1][si2][sj2][0] == 0) {
            cout << "Queen can escape.\n";
        } else if (state[si1][sj1][si2][sj2][0] == 1) {
            cout << "Army can catch Queen.\n";
        } else {
            cout << "Queen can not escape and Army can not catch Queen.\n";
        }

        // rep(i1,0,h)rep(j1,0,w)rep(i2,0,h)rep(j2,0,w){
        //     cout << i1 << " " << j1 << ", " << i2 << " " << j2 << ", " << 0 << ": " << state[i1][j1][i2][j2][0] << endl;
        //     cout << i1 << " " << j1 << ", " << i2 << " " << j2 << ", " << 1 << ": " << state[i1][j1][i2][j2][1] << endl;
        // }
        // cout << flush;
    }
}
accuracy: 1
time_ms: 50
memory_kb: 9528
final_rank: 4

code_snippet: #include <iostream>
#include <queue>
#include <tuple>
using namespace std;

int H, W;
int ax, ay, bx, by;
char c[39][39];

// 後退解析
int dx[5] = { 0, 1, 0, -1, 0 };
int dy[5] = { 1, 0, -1, 0, 0 };
int dp[2002][2002][2];
queue<tuple<int, int, int>> Q;

void search(int idx1, int idx2, int turn) {
	int sx = (idx1 / W) + 1;
	int sy = (idx1 % W) + 1;
	int tx = (idx2 / W) + 1;
	int ty = (idx2 % W) + 1;

	// 探索
	bool flag = false;
	for (int i = 0; i < 5; i++) {
		int ux = sx, uy = sy, vx = tx, vy = ty;
		if (turn == 0) { ux += dx[i]; uy += dy[i]; }
		if (turn == 1) { vx += dx[i]; vy += dy[i]; }
		if (c[ux][uy] == '#' || c[vx][vy] == '#') continue;
		int nex1 = (ux - 1) * W + (uy - 1);
		int nex2 = (vx - 1) * W + (vy - 1);

		// 負けの状態に遷移できるか？
		if (dp[nex1][nex2][1 - turn] == -1) {
			dp[idx1][idx2][turn] = 1;
			Q.push(make_tuple(idx1, idx2, turn));
			return;
		}
		else if (dp[nex1][nex2][1 - turn] == 0) {
			flag = true;
		}
	}

	// どうしても負けてしまう
	if (flag == false) {
		dp[idx1][idx2][turn] = -1;
		Q.push(make_tuple(idx1, idx2, turn));
	}
}

void solve() {
	// 初期化
	for (int i = 0; i < H * W; i++) {
		for (int j = 0; j < H * W; j++) {
			dp[i][j][0] = 0; dp[i][j][1] = 0;
		}
	}

	// 勝ち・負けの状態を列挙
	for (int i = 0; i < H * W; i++) {
		for (int j = 0; j < H * W; j++) {
			int sx = (i / W) + 1;
			int sy = (i % W) + 1;
			int tx = (j / W) + 1;
			int ty = (j % W) + 1;
			if (c[sx][sy] == '#' || c[tx][ty] == '#') continue;
			if (sx == tx && sy == ty) {
				dp[i][j][0] = -1; Q.push(make_tuple(i, j, 0));
				dp[i][j][1] = 1; Q.push(make_tuple(i, j, 1));
			}
			else if (c[sx][sy] == 'E') { 
				dp[i][j][0] = 1; Q.push(make_tuple(i, j, 0));
			}
		}
	}

	// 後退解析
	while (!Q.empty()) {
		int pos1 = get<0>(Q.front());
		int pos2 = get<1>(Q.front());
		int turn = get<2>(Q.front()); Q.pop();
		int sx = (pos1 / W) + 1;
		int sy = (pos1 % W) + 1;
		int tx = (pos2 / W) + 1;
		int ty = (pos2 % W) + 1;
		for (int i = 0; i < 5; i++) {
			int ux = sx, uy = sy, vx = tx, vy = ty;
			if (turn == 0) { vx += dx[i]; vy += dy[i]; }
			if (turn == 1) { ux += dx[i]; uy += dy[i]; }
			if (c[ux][uy] == '#' || c[vx][vy] == '#') continue;
			int idx1 = (ux - 1) * W + (uy - 1);
			int idx2 = (vx - 1) * W + (vy - 1);
			if (dp[idx1][idx2][1 - turn] != 0) continue;
			search(idx1, idx2, 1 - turn);
		}
	}

	// 出力
	int cur1 = (ax - 1) * W + (ay - 1);
	int cur2 = (bx - 1) * W + (by - 1);
	if (dp[cur1][cur2][0] == 1) cout << "Queen can escape." << endl;
	if (dp[cur1][cur2][0] == 0) cout << "Queen can not escape and Army can not catch Queen." << endl;
	if (dp[cur1][cur2][0] == -1) cout << "Army can catch Queen." << endl;
}

int main() {
	while (true) {
		// 入力
		cin >> W >> H; if (H == 0 && W == 0) break;
		for (int i = 0; i <= H + 1; i++) {
			for (int j = 0; j <= W + 1; j++) c[i][j] = '#';
		}
		for (int i = 1; i <= H; i++) {
			for (int j = 1; j <= W; j++) {
				cin >> c[i][j];
				if (c[i][j] == 'Q') { ax = i; ay = j; c[i][j] = '.'; }
				if (c[i][j] == 'A') { bx = i; by = j; c[i][j] = '.'; }
			}
		}

		// 問題を解く
		solve();
	}
	return 0;
}
accuracy: 1
time_ms: 30
memory_kb: 12760
final_rank: 5

code_snippet: #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return true; } return false; }
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return true; } return false; }
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define mp make_pair
#define si(x) int(x.size())
const int mod=998244353,MAX=35,INF=1<<30;
int state[MAX][MAX][MAX][MAX][2];
int cnt[MAX][MAX][MAX][MAX][2];
vector<int> dh={-1,0,1,0,0},dw={0,1,0,-1,0};

int main() {
    
    std::ifstream in("text.txt");
    std::cin.rdbuf(in.rdbuf());
    cin.tie(0);
    ios::sync_with_stdio(false);
    
    while(1){
        int H,W;cin>>W>>H;
        if(H==0) break;
        vector<string> S(H);
        for(int i=0;i<H;i++) cin>>S[i];
        memset(state,0,sizeof(state));
        memset(cnt,0,sizeof(cnt));
        queue<vector<int>> Q01,Q02,Q11,Q12;
        for(int i=0;i<H;i++){
            for(int j=0;j<W;j++){
                if(S[i][j]=='#') continue;
                state[i][j][i][j][0]=2;
                Q02.push({i,j,i,j});
                
                if(S[i][j]!='E') continue;
                for(int k=0;k<H;k++){
                    for(int l=0;l<W;l++){
                        if(i==k&&j==l) continue;
                        if(S[k][l]=='#') continue;
                        state[i][j][k][l][0]=1;
                        Q01.push({i,j,k,l});
                    }
                }
            }
        }
        
        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 d=0;d<5;d++){
                            int toh=i+dh[d],tow=j+dw[d];
                            if(toh<0||toh>=H||tow<0||tow>=W||S[toh][tow]=='#') continue;
                            //if(toh==k&&tow==l) continue;
                            cnt[i][j][k][l][0]++;
                        }
                        
                        for(int d=0;d<5;d++){
                            int toh=k+dh[d],tow=l+dw[d];
                            if(toh<0||toh>=H||tow<0||tow>=W||S[toh][tow]=='#') continue;
                            //if(S[i][j]=='E'&&(i!=toh||j!=tow)) continue;
                            cnt[i][j][k][l][1]++;
                        }
                    }
                }
            }
        }
        
        while(si(Q01)+si(Q02)+si(Q11)+si(Q12)){
            //cout<<1<<endl;
            while(si(Q01)){
                auto u=Q01.front();Q01.pop();
                for(int k=0;k<5;k++){
                    int toh=u[2]+dh[k],tow=u[3]+dw[k];
                    if(toh<0||toh>=H||tow<0||tow>=W||S[toh][tow]=='#') continue;
                    cnt[u[0]][u[1]][toh][tow][1]--;
                    if(state[u[0]][u[1]][toh][tow][1]==0&&cnt[u[0]][u[1]][toh][tow][1]==0){
                        state[u[0]][u[1]][toh][tow][1]=1;
                        Q11.push({u[0],u[1],toh,tow});
                    }
                }
            }
            
            while(si(Q02)){
                auto u=Q02.front();Q02.pop();
                for(int k=0;k<5;k++){
                    int toh=u[2]+dh[k],tow=u[3]+dw[k];
                    if(toh<0||toh>=H||tow<0||tow>=W||S[toh][tow]=='#') continue;
                    if(state[u[0]][u[1]][toh][tow][1]==0){
                        state[u[0]][u[1]][toh][tow][1]=2;
                        Q12.push({u[0],u[1],toh,tow});
                    }
                }
            }
            
            while(si(Q11)){
                auto u=Q11.front();Q11.pop();
                for(int k=0;k<5;k++){
                    int toh=u[0]+dh[k],tow=u[1]+dw[k];
                    if(toh<0||toh>=H||tow<0||tow>=W||S[toh][tow]=='#') continue;
                    if(state[toh][tow][u[2]][u[3]][0]==0){
                        state[toh][tow][u[2]][u[3]][0]=1;
                        Q01.push({toh,tow,u[2],u[3]});
                    }
                }
            }
            
            while(si(Q12)){
                auto u=Q12.front();Q12.pop();
                for(int k=0;k<5;k++){
                    int toh=u[0]+dh[k],tow=u[1]+dw[k];
                    if(toh<0||toh>=H||tow<0||tow>=W||S[toh][tow]=='#') continue;
                    cnt[toh][tow][u[2]][u[3]][0]--;
                    if(state[toh][tow][u[2]][u[3]][0]==0&&cnt[toh][tow][u[2]][u[3]][0]==0){
                        state[toh][tow][u[2]][u[3]][0]=2;
                        Q02.push({toh,tow,u[2],u[3]});
                    }
                }
            }
        }
        
        int sh,sw,gh,gw;
        
        for(int i=0;i<H;i++){
            for(int j=0;j<W;j++){
                if(S[i][j]=='Q'){
                    sh=i;
                    sw=j;
                }
                if(S[i][j]=='A'){
                    gh=i;
                    gw=j;
                }
            }
        }
        
        if(state[sh][sw][gh][gw][0]==0){
            cout<<"Queen can not escape and Army can not catch Queen.\n";
        }else if(state[sh][sw][gh][gw][0]==1){
            cout<<"Queen can escape.\n";
        }else{
            cout<<"Army can catch Queen.\n";
        }
    }
    
}
accuracy: 1
time_ms: 100
memory_kb: 26872
final_rank: 8

code_snippet: #include <bits/stdc++.h>

using namespace std;

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

const string output[] = {
    "Queen can not escape and Army can not catch Queen.", 
    "Queen can escape.",
    "Army can catch Queen."
};

void solve() {
    int W, H;
    cin >> W >> H;

    if (H == 0 && W == 0) {
        exit(0);
    }

    vector<string> board(H);
    for (int i = 0; i < H; i++) {
        cin >> board[i];
    }

    // m = 0: queen moves first. m = 1: army moves first.
    auto id = [&](int qi, int qj, int ai, int aj, int m) -> int {
        return ((W * qi + qj) * H * W + (W * ai + aj)) * 2 + m;
    };

    auto id_inv = [&](int t) -> tuple<int, int, int, int, int> {
        int m = t % 2;
        t /= 2;
        int q = t / (H * W);
        int a = t % (H * W);
        int qi = q / W;
        int qj = q % W;
        int ai = a / W;
        int aj = a % W;
        return {qi, qj, ai, aj, m};
    };

    int N = H * W * H * W * 2;
    vector<vector<int>> adj_inv(N);
    vector<int> deg(N);
    vector<int> answer(N);  // 1: queen wins. 2: army wins. 0: otherwise.
    queue<int> q;
    for (int qi = 0; qi < H; qi++) {
        for (int qj = 0; qj < W; qj++) {
            if (board[qi][qj] == '#') continue;
            bool is_escape = (board[qi][qj] == 'E');
            for (int ai = 0; ai < H; ai++) {
                for (int aj = 0; aj < W; aj++) {
                    if (board[ai][aj] == '#') continue;
                    int t0 = id(qi, qj, ai, aj, 0);
                    int t1 = id(qi, qj, ai, aj, 1);
                    if (qi == ai && qj == aj) {
                        answer[t0] = 2;
                        q.push(t0);
                        answer[t1] = 2;
                        q.push(t1);
                    } else if (is_escape) {
                        answer[t0] = 1;
                        q.push(t0);
                    }

                    int qt = id(qi, qj, ai, aj, 0);
                    int at = id(qi, qj, ai, aj, 1);
                    adj_inv[at].push_back(qt);
                    deg[qt]++;
                    adj_inv[qt].push_back(at);
                    deg[at]++;
                    for (int m = 0; m < 2; m++) {
                        int t = id(qi, qj, ai, aj, m);
                        int nm = m ^ 1;
                        if (nm == 0) {
                            for (int i = 0; i < 4; i++) {
                                int di = ds[i];
                                int dj = ds[i + 1];
                                int nqi = qi + di;
                                int nqj = qj + dj;
                                if (0 <= nqi && nqi < H && 0 <= nqj &&
                                    nqj < W && board[nqi][nqj] != '#') {
                                    int nt = id(nqi, nqj, ai, aj, nm);
                                    adj_inv[t].push_back(nt);
                                    deg[nt]++;
                                }
                            }
                        } else {
                            for (int i = 0; i < 4; i++) {
                                int di = ds[i];
                                int dj = ds[i + 1];
                                int nai = ai + di;
                                int naj = aj + dj;
                                if (0 <= nai && nai < H && 0 <= naj &&
                                    naj < W && board[nai][naj] != '#') {
                                    int nt = id(qi, qj, nai, naj, nm);
                                    adj_inv[t].push_back(nt);
                                    deg[nt]++;
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    while (!q.empty()) {
        int t = q.front();
        int m = t % 2;
        q.pop();
        // auto [e1, e2, e3, e4, e5] = id_inv(t);
        // cerr << t << ' ' << e1 << ' ' << e2 << ' ' << e3 << ' ' << e4 << ' '
        //      << e5 << ' ' << answer[t] << endl;
        for (auto &&nt : adj_inv[t]) {
            if (answer[nt] == 0) {
                // cerr << nt << endl;
                deg[nt]--;
                if (m == 1) {
                    if (answer[t] == 1) {
                        answer[nt] = 1;
                        q.push(nt);
                    } else if (answer[t] == 2 && deg[nt] == 0) {
                        answer[nt] = 2;
                        q.push(nt);
                    }
                } else {
                    if (answer[t] == 2) {
                        answer[nt] = 2;
                        q.push(nt);
                    } else if (answer[t] == 1 && deg[nt] == 0) {
                        answer[nt] = 1;
                        q.push(nt);
                    }
                }
            }
        }
    }

    int sqi, sqj, sai, saj;
    for (int i = 0; i < H; i++) {
        for (int j = 0; j < W; j++) {
            if (board[i][j] == 'Q') {
                sqi = i;
                sqj = j;
            } else if (board[i][j] == 'A') {
                sai = i;
                saj = j;
            }
        }
    }

    cout << output[answer[id(sqi, sqj, sai, saj, 0)]] << endl;

    return;
}

int main() {
    while (true) {
        solve();
    }
}
accuracy: 1
time_ms: 50
memory_kb: 30796
final_rank: 9

code_snippet: /*	author:  Kite_kuma
	created: 2021.09.24 07:42:45 */

// #ifdef LOCAL
// #define _GLIBCXX_DEBUG
// #endif
#include <bits/stdc++.h>
using namespace std;

#pragma region macros

#define foa(s, v) for(auto &s : v)
#define all(v) (v).begin(), (v).end()
#define rall(v) (v).rbegin(), (v).rend()
#define popcnt(n) __builtin_popcountll((long long)n)

#define REPname(a, b, c, d, e, ...) e
#define rep(...) REPname(__VA_ARGS__, REP3, REP2, REP1, REP0)(__VA_ARGS__)
#define REP0(x) for(int Counter_in_rep_macro = 0; Counter_in_rep_macro < (x); ++Counter_in_rep_macro)
#define REP1(i, x) for(int i = 0; i < (x); ++i)
#define REP2(i, l, r) for(int i = (l); i < (r); ++i)
#define REP3(i, l, r, c) for(int i = (l); i < (r); i += (c))

#define DREPname(a, b, c, d, e, ...) e
#define drep(...) DREPname(__VA_ARGS__, DREP3, DREP2, DREP1)(__VA_ARGS__)
#define DREP1(i, x) for(int i = (x)-1; i >= 0; --i)
#define DREP2(i, l, r) for(int i = (r)-1; i >= (l); --i)
#define DREP3(i, l, r, c) for(int i = (r)-1; i >= (l); i -= (c))

#pragma endregion

#pragma region aliases

using ll = long long;
using ld = long double;
using ull = unsigned long long;
using vi = std::vector<int>;
using vvi = std::vector<std::vector<int>>;
using vvvi = std::vector<std::vector<std::vector<int>>>;
using vll = std::vector<ll>;
using vvll = std::vector<vll>;
using vvvll = std::vector<vvll>;
using pii = std::pair<int, int>;
using pll = std::pair<long long, long long>;
template <class T = ll>
using V = std::vector<T>;
template <class T = ll>
using VV = V<V<T>>;
template <class T = ll>
using VVV = V<V<V<T>>>;
template <class T = ll>
using pqup = std::priority_queue<T, std::vector<T>, std::greater<T>>;
template <class T = ll>
using pqdn = std::priority_queue<T>;

#pragma endregion

#pragma region constants

const int inf = 1e9;
const long long INF = 1e18;
const long double pi = acos(-1);
const char dl = '\n';
const char sp = ' ';
int dx[8] = {1, 0, -1, 0, 0, -1, -1, 1};
int dy[8] = {0, 1, 0, -1, 0, 1, -1, -1};

const int mod_1000000007 = 1000000007;
const int mod_998244353 = 998244353;

#pragma endregion

#pragma region basic_operation

template <class T0, class T1, class T2>
inline bool in_range(T0 x, T1 lef, T2 rig) {
	return ((lef <= x) && (x < rig));
}

template <class T>
inline bool chmin(T &a, T b) {
	if(a > b) {
		a = b;
		return true;
	}
	return false;
}
template <class T>
inline bool chmax(T &a, T b) {
	if(a < b) {
		a = b;
		return true;
	}
	return false;
}

void Yes(bool f = 1) { std::cout << (f ? "Yes" : "No") << '\n'; }
void No() { std::cout << "No\n"; }
void YES(bool f = 1) { std::cout << (f ? "YES" : "NO") << '\n'; }
void NO() { std::cout << "NO\n"; }

template <class T>
void drop(T answer) {
	std::cout << answer << '\n';
	exit(0);
}

void err(bool flag = true) {
	if(!flag) return;
	std::cout << -1 << '\n';
	exit(0);
}

template <class T>
void vout(std::vector<T> const &v, bool vertically = 0) {
	if(vertically) {
		for(auto const &a : v) {
			std::cout << a << '\n';
		}
		return;
	}
	for(auto it = v.begin(); it != v.end(); it++) {
		std::cout << (*it);
		if(it != v.end() - 1) {
			std::cout << ' ';
		}
	}
	std::cout << '\n';
	return;
}

inline void print() { std::cout << '\n'; }
template <class T>
inline void print(T x) {
	std::cout << x << '\n';
	return;
}
template <typename Head, typename... Tail>
void print(Head H, Tail... T) {
	std::cout << H << " ";
	print(T...);
}

template <class T>
void add(std::vector<T> &v, T val) {
	for(auto &a : v) a += val;
	return;
}

template <class T>
T dup(T a, T b) {
	assert(b != 0);
	return (a + b - 1) / b;
}

template <class T>
T greatest_lower_multiple(T x, T d) {
	if(d == 0) return 0;
	if(d < 0) d *= -1;
	T y = x % d;
	if(y < 0) y += d;
	return x - y;
}

template <class T>
T least_upper_multiple(T x, T d) {
	return -greatest_lower_multiple(-x, d);
}

long long POW(long long a, long long n) {
	long long res = 1;
	while(n > 0) {
		if(n & 1) res = res * a;
		a = a * a;
		n >>= 1;
	}
	return res;
}

long long modpow(long long a, long long n, long long mod) {	 // a^n mod
	assert(n >= 0 && mod);
	if(mod == 1) return 0LL;
	long long res = 1;
	a %= mod;
	while(n > 0) {
		if(n & 1) res = res * a % mod;
		a = a * a % mod;
		n >>= 1;
	}
	return res < 0 ? res + mod : res;
}

// return x which satisfies a * x % mod == gcd(a, mod)
// not (mod | a)
long long modinv(long long a, long long mod) {
	long long b = mod, u = 1, v = 0;
	while(b) {
		long long t = a / b;
		a -= t * b;
		std::swap(a, b);
		u -= t * v;
		std::swap(u, v);
	}
	u %= mod;
	if(u < 0) u += mod;
	return u;
}

template <class T>
int lb(const std::vector<T> &a, const T x) {
	return std::distance(a.begin(), std::lower_bound(a.begin(), a.end(), x));
}
template <class T>
int ub(const std::vector<T> &a, const T x) {
	return std::distance(a.begin(), std::upper_bound(a.begin(), a.end(), x));
}
template <class T>
void unq_sort(std::vector<T> &a) {
	std::sort(a.begin(), a.end());
	a.erase(std::unique(a.begin(), a.end()), a.end());
}
template <class T>
std::vector<int> press(std::vector<T> &a) {
	auto vec = a;
	unq_sort(vec);
	std::vector<int> ret;
	for(auto &v : a) ret.push_back(lb(vec, v));
	return ret;
}

#pragma endregion

#pragma region input
#define VEC(type, name, size) \
	vector<type> name(size);  \
	scanner::INPUT(name)
#define VVEC(type, name, h, w)                     \
	vector<vector<type>> name(h, vector<type>(w)); \
	scanner::INPUT(name)
#define INT(...)     \
	int __VA_ARGS__; \
	scanner::INPUT(__VA_ARGS__)
#define LL(...)            \
	long long __VA_ARGS__; \
	scanner::INPUT(__VA_ARGS__)
#define STR(...)        \
	string __VA_ARGS__; \
	scanner::INPUT(__VA_ARGS__)
#define CHR(...)      \
	char __VA_ARGS__; \
	scanner::INPUT(__VA_ARGS__)
#define DBL(...)        \
	double __VA_ARGS__; \
	scanner::INPUT(__VA_ARGS__)
#define LD(...)              \
	long double __VA_ARGS__; \
	scanner::INPUT(__VA_ARGS__)
#define TPL3(type0, type1, type2, name)   \
	std::tuple<type0, type1, type2> name; \
	scanner::INPUT(name);
#define TPL4(type0, type1, type2, type3, name)   \
	std::tuple<type0, type1, type2, type3> name; \
	scanner::INPUT(name);

namespace scanner {
template <class T>
void scan(T &a) {
	std::cin >> a;
}

template <class T, class L>
void scan(std::pair<T, L> &p) {
	scan(p.first);
	scan(p.second);
}

template <class T0, class T1, class T2>
void scan(std::tuple<T0, T1, T2> &p) {
	T0 t0;
	T1 t1;
	T2 t2;
	scan(t0);
	scan(t1);
	scan(t2);
	p = std::make_tuple(t0, t1, t2);
}

template <class T0, class T1, class T2, class T3>
void scan(std::tuple<T0, T1, T2, T3> &p) {
	T0 t0;
	T1 t1;
	T2 t2;
	T3 t3;
	scan(t0);
	scan(t1);
	scan(t2);
	scan(t3);
	p = std::make_tuple(t0, t1, t2, t3);
}

template <class T>
void scan(std::vector<T> &a) {
	for(auto &i : a) scan(i);
}

void INPUT() {}
template <class Head, class... Tail>
void INPUT(Head &head, Tail &... tail) {
	scan(head);
	INPUT(tail...);
}
}  // namespace scanner

template <typename T1, typename T2>
std::istream &operator>>(std::istream &is, std::pair<T1, T2> &p) {
	is >> p.first >> p.second;
	return is;
}
#pragma endregion

#pragma region debug

#pragma region output
template <typename T1, typename T2>
std::ostream &std::operator<<(std::ostream &os, const std::pair<T1, T2> &p) {
	os << p.first << " " << p.second;
	return os;
}
template <class T>
std::ostream &std::operator<<(std::ostream &os, const std::vector<T> &v) {
	for(int i = 0; i < (int)v.size(); i++) {
		if(i) os << " ";
		os << v[i];
	}
	return os;
}
#pragma endregion

#pragma region view

namespace viewer {
void view(const long long e) {
	if(e == INF)
		std::cerr << "INF";
	else if(e == -INF)
		std::cerr << "-INF";
	else
		std::cerr << e;
}

void view(const int e) {
	if(e == inf)
		std::cerr << "inf";
	else if(e == -inf)
		std::cerr << "-inf";
	else
		std::cerr << e;
}

template <typename T>
void view(const T e) {
	std::cerr << e;
}

template <typename T, typename U>
void view(const std::pair<T, U> &p) {
	std::cerr << "(";
	view(p.first);
	std::cerr << ", ";
	view(p.second);
	std::cerr << ")";
}

template <class T0, class T1, class T2>
void view(const std::tuple<T0, T1, T2> &p) {
	std::cerr << "(";
	view(std::get<0>(p));
	std::cerr << ", ";
	view(std::get<1>(p));
	std::cerr << ", ";
	view(std::get<2>(p));
	std::cerr << ")";
}

template <class T0, class T1, class T2, class T3>
void view(const std::tuple<T0, T1, T2, T3> &p) {
	std::cerr << "(";
	view(std::get<0>(p));
	std::cerr << ", ";
	view(std::get<1>(p));
	std::cerr << ", ";
	view(std::get<2>(p));
	std::cerr << ", ";
	view(std::get<3>(p));
	std::cerr << ")";
}

template <typename T>
void view(const std::set<T> &s) {
	if(s.empty()) {
		std::cerr << "{ }";
		return;
	}
	std::cerr << "{ ";
	for(auto &t : s) {
		view(t);
		std::cerr << ", ";
	}
	std::cerr << "\b\b }";
}

template <typename T>
void view(const std::unordered_set<T> &s) {
	if(s.empty()) {
		std::cerr << "{ }";
		return;
	}
	std::cerr << "{ ";
	for(auto &t : s) {
		view(t);
		std::cerr << ", ";
	}
	std::cerr << "\b\b }";
}

template <typename T>
void view(const std::vector<T> &v) {
	if(v.empty()) {
		std::cerr << "{ }";
		return;
	}
	std::cerr << "{ ";
	for(const auto &e : v) {
		view(e);
		std::cerr << ", ";
	}
	std::cerr << "\b\b }";
}

template <typename T>
void view(const std::vector<std::vector<T>> &vv) {
	std::cerr << "{\n";
	for(const auto &v : vv) {
		std::cerr << "\t";
		view(v);
		std::cerr << '\n';
	}
	std::cerr << "}";
}

template <typename T, typename U>
void view(const std::vector<std::pair<T, U>> &v) {
	std::cerr << "{\n";
	for(const auto &c : v) {
		std::cerr << "\t(";
		view(c.first);
		std::cerr << ", ";
		view(c.second);
		std::cerr << ")\n";
	}
	std::cerr << "}";
}

template <class T0, class T1, class T2>
void view(const std::vector<std::tuple<T0, T1, T2>> &v) {
	if(v.empty()) {
		std::cerr << "{ }";
		return;
	}
	std::cerr << '{';
	for(const auto &t : v) {
		std::cerr << "\n\t";
		view(t);
		std::cerr << ",";
	}
	std::cerr << "\n}";
}

template <class T0, class T1, class T2, class T3>
void view(const std::vector<std::tuple<T0, T1, T2, T3>> &v) {
	if(v.empty()) {
		std::cerr << "{ }";
		return;
	}
	std::cerr << '{';
	for(const auto &t : v) {
		std::cerr << "\n\t";
		view(t);
		std::cerr << ",";
	}
	std::cerr << "\n}";
}

template <typename T, typename U>
void view(const std::map<T, U> &m) {
	std::cerr << "{\n";
	for(const auto &t : m) {
		std::cerr << "\t[";
		view(t.first);
		std::cerr << "] : ";
		view(t.second);
		std::cerr << '\n';
	}
	std::cerr << "}";
}

template <typename T, typename U>
void view(const std::unordered_map<T, U> &m) {
	std::cerr << "{\n";
	for(const auto &t : m) {
		std::cerr << "\t[";
		view(t.first);
		std::cerr << "] : ";
		view(t.second);
		std::cerr << '\n';
	}
	std::cerr << "}";
}
}  // namespace viewer

#pragma endregion

// when debugging : g++ foo.cpp -DLOCAL
#ifdef LOCAL
void debug_out() {}
template <typename Head, typename... Tail>
void debug_out(Head H, Tail... T) {
	viewer::view(H);
	std::cerr << ", ";
	debug_out(T...);
}
#define debug(...)                                                \
	do {                                                          \
		std::cerr << __LINE__ << " [" << #__VA_ARGS__ << "] : ["; \
		debug_out(__VA_ARGS__);                                   \
		std::cerr << "\b\b]\n";                                   \
	} while(0)
#define dump(x)                                      \
	do {                                             \
		std::cerr << __LINE__ << " " << #x << " : "; \
		viewer::view(x);                             \
		std::cerr << '\n';                           \
	} while(0)

#else
#define debug(...) (void(0))
#define dump(x) (void(0))
#endif

#pragma endregion

#pragma region modint

const int mod = mod_1000000007;

template <int mod>
struct ModInt {
	int x;
	ModInt() : x(0) {}
	ModInt(long long y) : x(y >= 0 ? y % mod : (mod - (-y) % mod) % mod) {}
	ModInt &operator+=(const ModInt &p) {
		if((x += p.x) >= mod) x -= mod;
		return *this;
	}
	ModInt &operator-=(const ModInt &p) {
		if((x += mod - p.x) >= mod) x -= mod;
		return *this;
	}
	ModInt &operator*=(const ModInt &p) {
		x = (int)(1LL * x * p.x % mod);
		return *this;
	}
	ModInt &operator/=(const ModInt &p) {
		*this *= p.inverse();
		return *this;
	}
	ModInt operator-() const { return ModInt(-x); }
	ModInt operator+(const ModInt &p) const { return ModInt(*this) += p; }
	ModInt operator-(const ModInt &p) const { return ModInt(*this) -= p; }
	ModInt operator*(const ModInt &p) const { return ModInt(*this) *= p; }
	ModInt operator/(const ModInt &p) const { return ModInt(*this) /= p; }
	bool operator==(const ModInt &p) const { return x == p.x; }
	bool operator!=(const ModInt &p) const { return x != p.x; }
	ModInt inverse() const {
		int a = x, b = mod, u = 1, v = 0, t;
		while(b > 0) {
			t = a / b;
			swap(a -= t * b, b);
			swap(u -= t * v, v);
		}
		return ModInt(u);
	}
	ModInt pow(long long n) const {
		ModInt ret(1), mul(x);
		while(n > 0) {
			if(n & 1) ret *= mul;
			mul *= mul;
			n >>= 1;
		}
		return ret;
	}
	friend ostream &operator<<(ostream &os, const ModInt &p) { return os << p.x; }
	friend istream &operator>>(istream &is, ModInt &a) {
		long long t;
		is >> t;
		a = ModInt<mod>(t);
		return (is);
	}
	static int get_mod() { return mod; }
};
using mint = ModInt<mod>;

#pragma endregion

vector<vector<int>> grid;
const int len = 30;
int res[len][len][len][len][2];
int chk[len][len][len][len][2];
int out_deg[len][len][len][len][2];

string solve(int h, int w) {
	const int wall = 0;
	const int floor = 1;
	const int escape = 2;

	grid.assign(h, vi(w, 0));

	pair<int, int> queen_start, army_start;
	rep(i, h) rep(j, w) {
		char c;
		cin >> c;
		if(c == 'Q')
			queen_start = pair(i, j);
		else if(c == 'A')
			army_start = pair(i, j);

		if(c == '#') {
			grid[i][j] = wall;
		} else if(c == 'E') {
			grid[i][j] = escape;
		} else {
			grid[i][j] = floor;
		}
	}

	vector states(h, vector(w, vector(h, vector(w, vector<vector<tuple<int, int, int, int, int>>>(2)))));
	auto states_rev = states;

	// 1: queen wins, -1: army wins, 0: tie, -2: unknown
	enum { queen_wins = 1, army_wins = -1, draw = 0, unknown = -2 };

	rep(i, len) rep(j, len) rep(k, len) rep(l, len) rep(m, 2) {
		res[i][j][k][l][m] = unknown;
		chk[i][j][k][l][m] = 0;
		out_deg[i][j][k][l][m] = 0;
	}

	queue<tuple<int, int, int, int, int>> q;

	rep(i, h) rep(j, w) rep(k, h) rep(l, w) rep(t, 2) {
		if(grid[i][j] == wall || grid[k][l] == wall) continue;
		auto &tmp = states[i][j][k][l][t];
		if(t == 1) {  // q's turn
			for(int dir = 0; dir < 5; dir++) {
				int u = i + dx[dir];
				int v = j + dy[dir];
				if(u < 0 || u >= h || v < 0 || v >= w) continue;
				if(grid[u][v] == wall) continue;
				tmp.emplace_back(u, v, k, l, 0);
				states_rev[u][v][k][l][0].emplace_back(i, j, k, l, t);
				out_deg[i][j][k][l][t]++;
			}
		} else {
			for(int dir = 0; dir < 5; dir++) {
				int u = k + dx[dir];
				int v = l + dy[dir];
				if(u < 0 || u >= h || v < 0 || v >= w) continue;
				if(grid[u][v] == wall) continue;
				tmp.emplace_back(i, j, u, v, 1);
				states_rev[i][j][u][v][1].emplace_back(i, j, k, l, t);
				out_deg[i][j][k][l][t]++;
			}
		}
		auto &r = res[i][j][k][l][t];
		auto &c = chk[i][j][k][l][t];
		if(i == k && j == l) {
			r = army_wins;
			q.emplace(i, j, k, l, t);
			c = 1;
		} else if(grid[i][j] == escape && t == 1) {
			r = queen_wins;
			q.emplace(i, j, k, l, t);
			c = 1;
		}
	}

	while(!q.empty()) {
		int qx, qy, ax, ay, t;
		tie(qx, qy, ax, ay, t) = q.front();
		q.pop();

		const int &result = res[qx][qy][ax][ay][t];

		debug(qx, qy, ax, ay, t, result);

		if(pair(qx, qy) == queen_start && pair(ax, ay) == army_start && t == 1) {
			if(result == queen_wins) {
				return "Queen can escape.";
			} else {
				return "Army can catch Queen.";
			}
		}

		for(auto [pre_qx, pre_qy, pre_ax, pre_ay, pre_t] : states_rev[qx][qy][ax][ay][t]) {
			int &c = chk[pre_qx][pre_qy][pre_ax][pre_ay][pre_t];
			if(c) continue;
			int &nxt_result = res[pre_qx][pre_qy][pre_ax][pre_ay][pre_t];
			if(t && result == army_wins || !t && result == queen_wins) {
				nxt_result = result;
				q.emplace(pre_qx, pre_qy, pre_ax, pre_ay, pre_t);
				c = 1;
			} else if(!(--out_deg[pre_qx][pre_qy][pre_ax][pre_ay][pre_t])) {
				nxt_result = (pre_t ? army_wins : queen_wins);
				q.emplace(pre_qx, pre_qy, pre_ax, pre_ay, pre_t);
				c = 1;
			}
		}
	}

	return "Queen can not escape and Army can not catch Queen.";
}

int main() {
	std::ios::sync_with_stdio(false);
	std::cin.tie(nullptr);
	std::cout << std::fixed << std::setprecision(15);
	srand((unsigned)time(NULL));

	int w, h;
	while(cin >> w >> h && w && h) {
		debug(w, h);
		cout << solve(h, w) << dl;
	}

	return 0;
}
accuracy: 1
time_ms: 650
memory_kb: 103940
final_rank: 18

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

#define x first
#define y second

int main() {
    int W, H;
    while (cin >> W >> H, W) {
        vector<string> S(H);
        for (auto&& s : S) {
            cin >> s;
        }
        pair<int, int> Q, A;
        vector<pair<int, int>> E;
        for (int x = 0; x < H; x++) {
            for (int y = 0; y < W; y++) {
                char c = S[x][y];
                if (c == 'Q')
                    Q = {x, y};
                if (c == 'A')
                    A = {x, y};
                if (c == 'E')
                    E.emplace_back(x, y);
            }
        }
        auto [Qx, Qy] = Q;
        auto [Ax, Ay] = A;

        const int dx[5] = {0, 0, 1, -1, 0}, dy[5] = {1, -1, 0, 0, 0};
        vector G(H, vector(W, vector(H, vector(W, vector(2, -1)))));
        vector updated(H, vector(W, vector(H, vector(W, vector(2, false)))));

        for (int qx = 0; qx < H; qx++) {
            for (int qy = 0; qy < W; qy++) {
                for (int ax = 0; ax < H; ax++) {
                    for (int ay = 0; ay < W; ay++) {
                        char qc = S[qx][qy], ac = S[ax][ay];
                        if (qc == '#' || ac == '#')
                            continue;
                        pair<int, int> q{qx, qy}, a{ax, ay};
                        auto& g0 = G[qx][qy][ax][ay][0];
                        auto& g1 = G[qx][qy][ax][ay][1];
                        if (q == a) {
                            g0 = 1;
                            g1 = 1;
                        } else if (qc == 'E')
                            g0 = 0;
                    }
                }
            }
        }

        using T = tuple<pair<int, int>, pair<int, int>, int>;

        auto ok = [&](pair<int, int> p) {
            auto [x, y] = p;
            return x >= 0 && x < H && y >= 0 && y < W && S[x][y] != '#';
        };

        auto adjnxt = [&](T tup) {
            auto [q, a, t] = tup;
            vector<T> ret;
            if (t == 0) {
                for (int i = 0; i < 5; i++) {
                    pair<int, int> nq{q.x + dx[i], q.y + dy[i]};
                    if (ok(nq))
                        ret.emplace_back(nq, a, !t);
                }
            } else {
                for (int i = 0; i < 5; i++) {
                    pair<int, int> na{a.x + dx[i], a.y + dy[i]};
                    if (ok(na))
                        ret.emplace_back(q, na, !t);
                }
            }
            return ret;
        };
        auto adjbef = [&](T tup) {
            auto [q, a, t] = tup;
            vector<T> ret;
            if (t == 1) {
                for (int i = 0; i < 5; i++) {
                    pair<int, int> nq{q.x + dx[i], q.y + dy[i]};
                    if (ok(nq))
                        ret.emplace_back(nq, a, !t);
                }
            } else {
                for (int i = 0; i < 5; i++) {
                    pair<int, int> na{a.x + dx[i], a.y + dy[i]};
                    if (ok(na))
                        ret.emplace_back(q, na, !t);
                }
            }
            return ret;
        };

        queue<T> que;
        for (int qx = 0; qx < H; qx++) {
            for (int qy = 0; qy < W; qy++) {
                for (int ax = 0; ax < H; ax++) {
                    for (int ay = 0; ay < W; ay++) {
                        for (int t = 0; t < 2; t++) {
                            int g = G[qx][qy][ax][ay][t];
                            pair<int, int> q{qx, qy}, a{ax, ay};
                            if (g != -1)
                                que.emplace(q, a, t);
                        }
                    }
                }
            }
        }

        while (!que.empty()) {
            auto tup = que.front();
            que.pop();
            auto [q, a, t] = tup;
            auto [qx, qy] = q;
            auto [ax, ay] = a;
            auto upd = updated[qx][qy][ax][ay][t];
            if (upd)
                continue;
            auto Vadjnxt = adjnxt(tup);
            auto& g = G[qx][qy][ax][ay][t];
            if (g == -1) {
                bool seenall = true, canwin = false;
                for (auto&& nxt : Vadjnxt) {
                    auto [nq, na, nt] = nxt;
                    auto [nqx, nqy] = nq;
                    auto [nax, nay] = na;
                    auto ng = G[nqx][nqy][nax][nay][nt];
                    if (ng == -1)
                        seenall = false;
                    if (ng == t) {
                        canwin = true;
                        break;
                    }
                }
                if (canwin)
                    g = t;
                else if (seenall)
                    g = !t;
            }
            if (g != -1) {
                updated[qx][qy][ax][ay][t] = true;

                auto Vadjbef = adjbef(tup);
                for (auto bef : Vadjbef) {
                    que.emplace(bef);
                }
            }
        }
        int ans = G[Qx][Qy][Ax][Ay][0];
        if (ans == 0)
            cout << "Queen can escape." << endl;
        if (ans == 1)
            cout << "Army can catch Queen." << endl;
        if (ans == -1)
            cout << "Queen can not escape and Army can not catch Queen." << endl;
    }
}
accuracy: 1
time_ms: 450
memory_kb: 57600
final_rank: 16

code_snippet: #include <bits/stdc++.h>
using namespace std;
vector<int> dx = {1, 0, -1, 0, 0};
vector<int> dy = {0, 1, 0, -1, 0};
int main(){
  while (true){
    int W, H;
    cin >> W >> H;
    if (W == 0 && H == 0){
      break;
    }
    vector<string> S(H);
    for (int i = 0; i < H; i++){
      cin >> S[i];
    }
    vector<vector<vector<vector<vector<int>>>>> deg(2, vector<vector<vector<vector<int>>>>(H, vector<vector<vector<int>>>(W, vector<vector<int>>(H, vector<int>(W, 0)))));
    vector<vector<vector<vector<vector<int>>>>> dp(2, vector<vector<vector<vector<int>>>>(H, vector<vector<vector<int>>>(W, vector<vector<int>>(H, vector<int>(W, 0)))));
    queue<tuple<int, int, int, int, int>> Q;
    for (int qx = 0; qx < H; qx++){
      for (int qy = 0; qy < W; qy++){
        for (int ax = 0; ax < H; ax++){
          for (int ay = 0; ay < W; ay++){
            if (S[qx][qy] != '#' && S[ax][ay] != '#'){
              if (qx == ax && qy == ay){
                dp[0][qx][qy][ax][ay] = -1;
                Q.push(make_tuple(0, qx, qy, ax, ay));
                dp[1][qx][qy][ax][ay] = 1;
                Q.push(make_tuple(1, qx, qy, ax, ay));
              } else {
                if (S[qx][qy] == 'E'){
                  dp[0][qx][qy][ax][ay] = 1;
                  Q.push(make_tuple(0, qx, qy, ax, ay));
                } else {
                  for (int i = 0; i < 5; i++){
                    int qx2 = qx + dx[i];
                    int qy2 = qy + dy[i];
                    if (0 <= qx2 && qx2 < H && 0 <= qy2 && qy2 < W){
                      if (S[qx2][qy2] != '#'){
                        deg[0][qx][qy][ax][ay]++;
                      } 
                    }
                  }
                }
                for (int i = 0; i < 5; i++){
                  int ax2 = ax + dx[i];
                  int ay2 = ay + dy[i];
                  if (0 <= ax2 && ax2 < H && 0 <= ay2 && ay2 < W){
                    if (S[ax2][ay2] != '#'){
                      deg[1][qx][qy][ax][ay]++;
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
    while (!Q.empty()){
      int t = get<0>(Q.front());
      int qx = get<1>(Q.front());
      int qy = get<2>(Q.front());
      int ax = get<3>(Q.front());
      int ay = get<4>(Q.front());
      Q.pop();
      if (t == 0){
        for (int i = 0; i < 5; i++){
          int ax2 = ax + dx[i];
          int ay2 = ay + dy[i];
          if (0 <= ax2 && ax2 < H && 0 <= ay2 && ay2 < W){
            if (S[ax2][ay2] != '#'){
              if (dp[1][qx][qy][ax2][ay2] == 0){
                if (dp[0][qx][qy][ax][ay] == -1){
                  dp[1][qx][qy][ax2][ay2] = 1;
                  Q.push(make_tuple(1, qx, qy, ax2, ay2));
                }
                if (dp[0][qx][qy][ax][ay] == 1){
                  deg[1][qx][qy][ax2][ay2]--;
                  if (deg[1][qx][qy][ax2][ay2] == 0){
                    dp[1][qx][qy][ax2][ay2] = -1;
                    Q.push(make_tuple(1, qx, qy, ax2, ay2));
                  }
                }
              }
            }
          }
        }
      }
      if (t == 1){
        for (int i = 0; i < 5; i++){
          int qx2 = qx + dx[i];
          int qy2 = qy + dy[i];
          if (0 <= qx2 && qx2 < H && 0 <= qy2 && qy2 < W){
            if (S[qx2][qy2] != '#'){
              if (dp[0][qx2][qy2][ax][ay] == 0){
                if (dp[1][qx][qy][ax][ay] == -1){
                  dp[0][qx2][qy2][ax][ay] = 1;
                  Q.push(make_tuple(0, qx2, qy2, ax, ay));
                }
                if (dp[1][qx][qy][ax][ay] == 1){
                  deg[0][qx2][qy2][ax][ay]--;
                  if (deg[0][qx2][qy2][ax][ay] == 0){
                    dp[0][qx2][qy2][ax][ay] = -1;
                    Q.push(make_tuple(0, qx2, qy2, ax, ay));
                  }
                }
              }
            }
          }
        }
      }
    }
    int qx, qy, ax, ay;
    for (int i = 0; i < H; i++){
      for (int j = 0; j < W; j++){
        if (S[i][j] == 'Q'){
          qx = i;
          qy = j;
        }
        if (S[i][j] == 'A'){
          ax = i;
          ay = j;
        }
      }
    }
    if (dp[0][qx][qy][ax][ay] == 1){
      cout << "Queen can escape." << endl;
    } else if (dp[0][qx][qy][ax][ay] == -1){
      cout << "Army can catch Queen." << endl;
    } else {
      cout << "Queen can not escape and Army can not catch Queen." << endl;
    }
  }
}
accuracy: 1
time_ms: 90
memory_kb: 14460
final_rank: 6

code_snippet: #pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#include<iostream>
#include<string>
#include<cstdio>
#include<vector>
#include<cmath>
#include<algorithm>
#include<functional>
#include<iomanip>
#include<queue>
#include<ciso646>
#include<random>
#include<map>
#include<set>
#include<bitset>
#include<stack>
#include<unordered_map>
#include<unordered_set>
#include<utility>
#include<cassert>
#include<complex>
#include<numeric>
#include<array>
using namespace std;

//#define int long long
typedef long long ll;

typedef unsigned long long ul;
typedef unsigned int ui;
constexpr ll mod = 1000000007;
const ll INF = mod * mod;
typedef pair<int, int>P;
#define stop char nyaa;cin>>nyaa;
#define rep(i,n) for(int i=0;i<n;i++)
#define per(i,n) for(int i=n-1;i>=0;i--)
#define Rep(i,sta,n) for(int i=sta;i<n;i++)
#define rep1(i,n) for(int i=1;i<=n;i++)
#define per1(i,n) for(int i=n;i>=1;i--)
#define Rep1(i,sta,n) for(int i=sta;i<=n;i++)
#define all(v) (v).begin(),(v).end()
typedef pair<ll, ll> LP;
typedef long double ld;
typedef pair<ld, ld> LDP;
const ld eps = 1e-12;
const ld pi = acosl(-1.0);

ll mod_pow(ll x, ll n, ll m = mod) {
	if (n < 0) {
		ll res = mod_pow(x, -n, m);
		return mod_pow(res, m - 2, m);
	}
	if (abs(x) >= m)x %= m;
	if (x < 0)x += m;
	ll res = 1;
	while (n) {
		if (n & 1)res = res * x % m;
		x = x * x % m; n >>= 1;
	}
	return res;
}
struct modint {
	ll n;
	modint() :n(0) { ; }
	modint(ll m) :n(m) {
		if (n >= mod)n %= mod;
		else if (n < 0)n = (n % mod + mod) % mod;
	}
	operator int() { return n; }
};
bool operator==(modint a, modint b) { return a.n == b.n; }
modint operator+=(modint& a, modint b) { a.n += b.n; if (a.n >= mod)a.n -= mod; return a; }
modint operator-=(modint& a, modint b) { a.n -= b.n; if (a.n < 0)a.n += mod; return a; }
modint operator*=(modint& a, modint b) { a.n = ((ll)a.n * b.n) % mod; return a; }
modint operator+(modint a, modint b) { return a += b; }
modint operator-(modint a, modint b) { return a -= b; }
modint operator*(modint a, modint b) { return a *= b; }
modint operator^(modint a, ll n) {
	if (n == 0)return modint(1);
	modint res = (a * a) ^ (n / 2);
	if (n % 2)res = res * a;
	return res;
}

ll inv(ll a, ll p) {
	return (a == 1 ? 1 : (1 - p * inv(p % a, a)) / a + p);
}
modint operator/(modint a, modint b) { return a * modint(inv(b, mod)); }
modint operator/=(modint& a, modint b) { a = a / b; return a; }
const int max_n = 1 << 1;
modint fact[max_n], factinv[max_n];
void init_f() {
	fact[0] = modint(1);
	for (int i = 0; i < max_n - 1; i++) {
		fact[i + 1] = fact[i] * modint(i + 1);
	}
	factinv[max_n - 1] = modint(1) / fact[max_n - 1];
	for (int i = max_n - 2; i >= 0; i--) {
		factinv[i] = factinv[i + 1] * modint(i + 1);
	}
}
modint comb(int a, int b) {
	if (a < 0 || b < 0 || a < b)return 0;
	return fact[a] * factinv[b] * factinv[a - b];
}
modint combP(int a, int b) {
	if (a < 0 || b < 0 || a < b)return 0;
	return fact[a] * factinv[a - b];
}

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

struct ste {
	int x1, y1, x2, y2;
};
int h, w;
bool used[30][30][30][30];
void solve() {
	vector<string> s(h);
	rep(i, h)cin >> s[i];
	auto isvalid = [&](int i, int j) {
		if (i < 0 || i >= h || j < 0 || j >= w || s[i][j] == '#')return false;
		return true;
	};
	auto push_next = [&](queue<ste>& q, int x1, int y1, int x2, int y2) {
		rep(d1, 5)rep(d2, 5) {
			int nx1 = x1 + dx[d1];
			int ny1 = y1 + dy[d1];
			int nx2 = x2 + dx[d2];
			int ny2 = y2 + dy[d2];
			if (isvalid(nx1, ny1) && isvalid(nx2, ny2)) {
				q.push({ nx1,ny1,nx2,ny2 });
			}
		}
	};
	int qx, qy;
	int ax, ay;
	rep(i, h)rep(j, w) {
		if (s[i][j] == 'Q') {
			qx = i, qy = j;
		}
		if (s[i][j] == 'A') {
			ax = i, ay = j;
		}
	}
	//escape
	{
		rep(i, h)rep(j, w)rep(k, h)rep(l, w)used[i][j][k][l] = false;
		auto isok = [&](int x1, int y1, int x2, int y2)->bool {
			rep(d1, 5) {
				int nx1 = x1 + dx[d1];
				int ny1 = y1 + dy[d1];
				if (!isvalid(nx1, ny1))continue;
				if (nx1 == x2 && ny1 == y2)continue;
				bool f = true;
				rep(d2, 5) {
					int nx2 = x2 + dx[d2];
					int ny2 = y2 + dy[d2];
					if (!isvalid(nx2, ny2))continue;
					if (!used[nx1][ny1][nx2][ny2])f = false;
				}
				if (f)return true;
			}
			return false;
		};
		queue<ste> q;
		rep(i, h)rep(j, w)if (s[i][j] == 'E') {
			rep(k, h)rep(l, w) {
				if (i == k && j == l)continue;
				if (isvalid(k, l)) {
					used[i][j][k][l] = true;
					push_next(q, i, j, k, l);
				}
			}
		}
		while (!q.empty()) {
			ste s = q.front(); q.pop();
			if (used[s.x1][s.y1][s.x2][s.y2])continue;
			if (isok(s.x1, s.y1, s.x2, s.y2)) {
				used[s.x1][s.y1][s.x2][s.y2] = true;
				push_next(q, s.x1, s.y1, s.x2, s.y2);
			}
		}
		if (used[qx][qy][ax][ay]) {
			cout << "Queen can escape.\n";
			return;
		}
	}
	{
		rep(i, h)rep(j, w)rep(k, h)rep(l, w)used[i][j][k][l] = false;
		auto isok = [&](int x1, int y1, int x2, int y2)->bool {
			rep(d1, 5) {
				int nx1 = x1 + dx[d1];
				int ny1 = y1 + dy[d1];
				if (!isvalid(nx1, ny1))continue;
				if (nx1 == x2 && ny1 == y2)continue;
				bool f = false;
				rep(d2, 5) {
					int nx2 = x2 + dx[d2];
					int ny2 = y2 + dy[d2];
					if (!isvalid(nx2, ny2))continue;
					if (used[nx1][ny1][nx2][ny2]) {
						f = true;
					}
				}
				if (!f)return false;
			}
			return true;
		};
		queue<ste> q;
		rep(i, h)rep(j, w) {
			if (isvalid(i, j)) {
				used[i][j][i][j] = true;
				push_next(q, i, j, i, j);
			}
		}
		while (!q.empty()) {
			ste s = q.front(); q.pop();
			if (used[s.x1][s.y1][s.x2][s.y2])continue;
			if (isok(s.x1, s.y1, s.x2, s.y2)) {
				used[s.x1][s.y1][s.x2][s.y2] = true;
				push_next(q, s.x1, s.y1, s.x2, s.y2);
			}
		}
		if (used[qx][qy][ax][ay]) {
			cout << "Army can catch Queen." << "\n";
			return;
		}
	}
	cout << "Queen can not escape and Army can not catch Queen." << "\n";
}


signed main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout << fixed << setprecision(12);
	//init_f();
	//init();
	//expr();
	//int t; cin >> t;rep(i,t)
	while (cin >> w >> h, h)
		solve();
	return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 4328
final_rank: 2

code_snippet: #include <bits/stdc++.h>
// created [2020/03/09] 22:05:43
#pragma GCC diagnostic ignored "-Wsign-compare"
#pragma GCC diagnostic ignored "-Wsign-conversion"

using i32   = int32_t;
using i64   = int64_t;
using u32   = uint32_t;
using u64   = uint64_t;
using uint  = unsigned int;
using usize = std::size_t;
using ll    = long long;
using ull   = unsigned long long;
using ld    = long double;
template<typename T, usize n>
using arr = T (&)[n];
template<typename T, usize n>
using c_arr = const T (&)[n];
template<typename T>
using max_heap = std::priority_queue<T>;
template<typename T>
using min_heap = std::priority_queue<T, std::vector<T>, std::greater<T>>;
template<typename T> constexpr T popcount(const T u) { return u ? static_cast<T>(__builtin_popcountll(static_cast<u64>(u))) : static_cast<T>(0); }
template<typename T> constexpr T log2p1(const T u) { return u ? static_cast<T>(64 - __builtin_clzll(static_cast<u64>(u))) : static_cast<T>(0); }
template<typename T> constexpr T msbp1(const T u) { return log2p1(u); }
template<typename T> constexpr T lsbp1(const T u) { return __builtin_ffsll(u); }
template<typename T> constexpr T clog(const T u) { return u ? log2p1(u - 1) : static_cast<T>(u); }
template<typename T> constexpr bool ispow2(const T u) { return u and (static_cast<u64>(u) & static_cast<u64>(u - 1)) == 0; }
template<typename T> constexpr T ceil2(const T u) { return static_cast<T>(1) << clog(u); }
template<typename T> constexpr T floor2(const T u) { return u == 0 ? static_cast<T>(0) : static_cast<T>(1) << (log2p1(u) - 1); }
template<typename T> constexpr bool btest(const T mask, const usize ind) { return static_cast<bool>((static_cast<u64>(mask) >> ind) & static_cast<u64>(1)); }
template<typename T> void bset(T& mask, const usize ind) { mask |= (static_cast<T>(1) << ind); }
template<typename T> void breset(T& mask, const usize ind) { mask &= ~(static_cast<T>(1) << ind); }
template<typename T> void bflip(T& mask, const usize ind) { mask ^= (static_cast<T>(1) << ind); }
template<typename T> void bset(T& mask, const usize ind, const bool b) { (b ? bset(mask, ind) : breset(mask, ind)); }
template<typename T> constexpr T bcut(const T mask, const usize ind) { return ind == 0 ? static_cast<T>(0) : static_cast<T>((static_cast<u64>(mask) << (64 - ind)) >> (64 - ind)); }
template<typename T> bool chmin(T& a, const T& b) { return (a > b ? a = b, true : false); }
template<typename T> bool chmax(T& a, const T& b) { return (a < b ? a = b, true : false); }
constexpr unsigned int mod                  = 1000000007;
template<typename T> constexpr T inf_v      = std::numeric_limits<T>::max() / 4;
template<typename Real> constexpr Real pi_v = Real{3.141592653589793238462643383279502884};
auto mfp = [](auto&& f) { return [=](auto&&... args) { return f(f, std::forward<decltype(args)>(args)...); }; };

template<typename T>
T in()
{
    T v;
    return std::cin >> v, v;
}
template<typename T, typename Uint, usize n, usize i>
T in_v(typename std::enable_if<(i == n), c_arr<Uint, n>>::type) { return in<T>(); }
template<typename T, typename Uint, usize n, usize i>
auto in_v(typename std::enable_if<(i < n), c_arr<Uint, n>>::type& szs)
{
    const usize s = (usize)szs[i];
    std::vector<decltype(in_v<T, Uint, n, i + 1>(szs))> ans(s);
    for (usize j = 0; j < s; j++) { ans[j] = in_v<T, Uint, n, i + 1>(szs); }
    return ans;
}
template<typename T, typename Uint, usize n>
auto in_v(c_arr<Uint, n> szs) { return in_v<T, Uint, n, 0>(szs); }
template<typename... Types>
auto in_t() { return std::tuple<std::decay_t<Types>...>{in<Types>()...}; }
struct io_init
{
    io_init()
    {
        std::cin.tie(nullptr), std::ios::sync_with_stdio(false);
        std::cout << std::fixed << std::setprecision(20);
    }
    void clear()
    {
        std::cin.tie(), std::ios::sync_with_stdio(true);
    }
} io_setting;

int out() { return 0; }
template<typename T>
int out(const T& v) { return std::cout << v, 0; }
template<typename T>
int out(const std::vector<T>& v)
{
    for (usize i = 0; i < v.size(); i++) {
        if (i > 0) { std::cout << ' '; }
        out(v[i]);
    }
    return 0;
}
template<typename T1, typename T2>
int out(const std::pair<T1, T2>& v) { return out(v.first), std::cout << ' ', out(v.second), 0; }
template<typename T, typename... Args>
int out(const T& v, const Args... args) { return out(v), std::cout << ' ', out(args...), 0; }
template<typename... Args>
int outln(const Args... args) { return out(args...), std::cout << '\n', 0; }
template<typename... Args>
int outel(const Args... args) { return out(args...), std::cout << std::endl, 0; }
#    define SHOW(...) static_cast<void>(0)
constexpr ull TEN(const usize n) { return n == 0 ? 1ULL : TEN(n - 1) * 10ULL; }

template<typename T, typename Uint, usize n, usize i>
auto make_v(typename std::enable_if<(i == n), c_arr<Uint, n>>::type, const T& v = T{}) { return v; }
template<typename T, typename Uint, usize n, usize i>
auto make_v(typename std::enable_if<(i < n), c_arr<Uint, n>>::type szs, const T& v = T{})
{
    const usize s = (usize)szs[i];
    return std::vector<decltype(make_v<T, Uint, n, i + 1>(szs, v))>(s, make_v<T, Uint, n, i + 1>(szs, v));
}
template<typename T, typename Uint, usize n>
auto make_v(c_arr<Uint, n> szs, const T& t = T{}) { return make_v<T, Uint, n, 0>(szs, t); }
int main()
{
    while (true) {
        auto W = in<int>(), H = in<int>();
        if (W == 0 and H == 0) { break; }
        const auto sss = in_v<std::string>({H});
        const int S    = H * W;
        auto enc       = [&](const int y, const int x) { return y * W + x; };
        const int SS   = S * S;
        auto encenc    = [&](const int a_tern, const int qy, const int qx, const int ay, const int ax) { return a_tern * SS + enc(qy, qx) * S + enc(ay, ax); };
        std::vector<std::vector<int>> g(2 * SS);
        std::vector<int> odim(2 * SS, 0);
        constexpr int dys[] = {-1, 0, 0, 1, 0};
        constexpr int dxs[] = {0, -1, 1, 0, 0};
        for (int a_tern = 0; a_tern < 2; a_tern++) {
            if (a_tern == 0) {
                for (int qy = 0; qy < H; qy++) {
                    for (int qx = 0; qx < W; qx++) {
                        if (sss[qy][qx] == '#') { continue; }
                        for (int ay = 0; ay < H; ay++) {
                            for (int ax = 0; ax < W; ax++) {
                                if (sss[ay][ax] == '#') { continue; }
                                if (qy == ay and qx == ax) { continue; }
                                const int ss = encenc(a_tern, qy, qx, ay, ax);
                                for (int qd = 0; qd < 5; qd++) {
                                    const int dqy = dys[qd], dqx = dxs[qd];
                                    const int nqy = qy + dqy, nqx = qx + dqx;
                                    if (nqy < 0 or nqy >= H or nqx < 0 or nqx >= W) { continue; }
                                    if (sss[nqy][nqx] == '#') { continue; }
                                    const int nss = encenc(1 - a_tern, nqy, nqx, ay, ax);
                                    g[nss].push_back(ss);
                                    odim[ss]++;
                                }
                            }
                        }
                    }
                }
            } else {
                for (int qy = 0; qy < H; qy++) {
                    for (int qx = 0; qx < W; qx++) {
                        if (sss[qy][qx] == '#') { continue; }
                        for (int ay = 0; ay < H; ay++) {
                            for (int ax = 0; ax < W; ax++) {
                                if (sss[ay][ax] == '#') { continue; }
                                const int ss = encenc(a_tern, qy, qx, ay, ax);
                                for (int ad = 0; ad < 5; ad++) {
                                    const int day = dys[ad], dax = dxs[ad];
                                    const int nay = ay + day, nax = ax + dax;
                                    if (nay < 0 or nay >= H or nax < 0 or nax >= W) { continue; }
                                    if (sss[nay][nax] == '#') { continue; }
                                    const int nss = encenc(1 - a_tern, qy, qx, nay, nax);
                                    g[nss].push_back(ss);
                                    odim[ss]++;
                                }
                            }
                        }
                    }
                }
            }
        }
        std::vector<int> win(SS * 2, 2);  // 0:lose, 1:win, 2:draw
        std::queue<int> Q;
        for (int a_tern = 0; a_tern < 2; a_tern++) {
            for (int qy = 0; qy < H; qy++) {
                for (int qx = 0; qx < W; qx++) {
                    if (sss[qy][qx] == '#') { continue; }
                    for (int ay = 0; ay < H; ay++) {
                        for (int ax = 0; ax < W; ax++) {
                            if (sss[ay][ax] == '#') { continue; }
                            const int ss = encenc(a_tern, qy, qx, ay, ax);
                            if (a_tern == 0) {
                                if (qy == ay and qx == ax) {
                                    win[ss] = 0;
                                    Q.push(ss);
                                } else if (sss[qy][qx] == 'E') {
                                    win[ss] = 1;
                                    Q.push(ss);
                                }
                            } else {
                                if (qy == ay and qx == ax) {
                                    win[ss] = 1;
                                    Q.push(ss);
                                }
                            }
                        }
                    }
                }
            }
        }
        while (not Q.empty()) {
            const int ss = Q.front();
            Q.pop();
            for (const int nss : g[ss]) {
                if (win[nss] != 2) { continue; }
                odim[nss]--;
                if (win[ss] == 0) {
                    win[nss] = 1;
                    Q.push(nss);
                } else if (win[ss] == 1) {
                    if (odim[nss] == 0) {
                        win[nss] = 0;
                        Q.push(nss);
                    }
                }
            }
        }
        int qy = -1, qx = -1, ay = -1, ax = -1;
        for (int i = 0; i < H; i++) {
            for (int j = 0; j < W; j++) {
                if (sss[i][j] == 'Q') { qy = i, qx = j; }
                if (sss[i][j] == 'A') { ay = i, ax = j; }
            }
        }
        const int init_ss = encenc(false, qy, qx, ay, ax);
        const int ans     = win[init_ss];
        if (ans == 0) {
            outln("Army can catch Queen.");
        } else if (ans == 1) {
            outln("Queen can escape.");
        } else {
            outln("Queen can not escape and Army can not catch Queen.");
        }
    }
    return 0;
}
accuracy: 1
time_ms: 90
memory_kb: 30408
final_rank: 10

code_snippet: #include <algorithm>
#include <bitset>
#include <cassert>
#include <chrono>
#include <climits>
#include <cmath>
#include <complex>
#include <cstring>
#include <deque>
#include <functional>
#include <iostream>
#include <iomanip>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <cstdint>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int,int> pii;
#define MP make_pair
#define PB push_back
#define inf 1000000007
#define rep(i,n) for(int i = 0; i < (int)(n); ++i)
#define all(x) (x).begin(),(x).end()

template<typename A, size_t N, typename T>
void Fill(A (&array)[N], const T &val){
    std::fill( (T*)array, (T*)(array+N), val );
}
 
template<class T> inline bool chmax(T &a, T b){
    if(a<b){
        a = b;
        return true;
    }
    return false;
}

template<class T> inline bool chmin(T &a, T b){
    if(a>b){
        a = b;
        return true;
    }
    return false;
}

char dp[31][31][31][31][151];
vector<string> s;
int n,m;
bool ok(int i,int j){
    if(i<0||i>=n)return false;
    if(j<0||j>=m)return false;
    if(s[i][j]=='#')return false;
    return true;
}
int dfs(int qi,int qj,int ai,int aj,int tur){
    if(tur==150){
        return 3;
    }
    if(dp[qi][qj][ai][aj][tur]!=0){
        return dp[qi][qj][ai][aj][tur];
    }
    if(qi==ai&&qj==aj){
        dp[qi][qj][ai][aj][tur]=2;
        return 2;
    }
    if(tur%2==0){
        if(s[qi][qj]=='E'){
            dp[qi][qj][ai][aj][tur] = 1;
            return 1;
        }
        vector<int> a;
        for(int i=-1;i<=1;i++){
            if(ok(qi+i,qj)){
                a.push_back(dfs(qi+i,qj,ai,aj,tur+1));
            }
        }
        for(int j=-1;j<=1;j++){
            if(ok(qi,qj+j)){
                a.push_back(dfs(qi,qj+j,ai,aj,tur+1));
            }
        }
        bool ss = 0;
        for(auto x:a){
            if(x==1){
                dp[qi][qj][ai][aj][tur] = 1;
                return 1;
            }else if(x==3){
                ss = 1;
            }
        }
        if(ss){
            dp[qi][qj][ai][aj][tur] = 3;
            return 3;
        }else{
            dp[qi][qj][ai][aj][tur] = 2;
            return 2;
        }
    }else{
        vector<int> a;
        for(int i=-1;i<=1;i++){
            if(ok(ai+i,aj)){
                a.push_back(dfs(qi,qj,ai+i,aj,tur+1));
            }
        }
        for(int j=-1;j<=1;j++){
            if(ok(ai,aj+j)){
                a.push_back(dfs(qi,qj,ai,aj+j,tur+1));
            }
        }
        bool ss = 0;
        for(auto x:a){
            if(x==2){
                dp[qi][qj][ai][aj][tur] = 2;
                return 2;
            }else if(x==3){
                ss = 1;
            }
        }
        if(ss){
            dp[qi][qj][ai][aj][tur] = 3;
            return 3;
        }else{
            dp[qi][qj][ai][aj][tur] = 1;
            return 1;
        }
    }

}


int main(){
    while(1){
        cin >> m >> n;
        if(n==0)break;
        rep(i,n){
            rep(j,m){
                rep(k,n){
                    rep(l,m){
                        rep(t,151){
                            dp[i][j][k][l][t] = 0;
                        }
                    }
                }
            }
        }
        s.resize(n);
        s.shrink_to_fit();
        rep(i,n){
            cin >> s[i];
        }
        int qi,qj,ai,aj;
        rep(i,n){
            rep(j,m){
                if(s[i][j]=='A'){
                    ai = i;
                    aj = j;
                }else if(s[i][j]=='Q'){
                    qi = i;
                    qj = j;
                } 
            }
        }
        int k = dfs(qi,qj,ai,aj,0);
        if(k==1){
            cout << "Queen can escape.\n";
        }else if(k==2){
            cout << "Army can catch Queen.\n";
        }else{
            cout << "Queen can not escape and Army can not catch Queen.\n";
        }
    }
    return 0;
}
accuracy: 1
time_ms: 2340
memory_kb: 105036
final_rank: 19

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

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

template<typename T>
std::vector<T> table(int n, T v) { return std::vector<T>(n, v); }

template <class... Args>
auto table(int n, Args... args) {
    auto val = table(args...);
    return std::vector<decltype(val)>(n, std::move(val));
}

enum {
    Escape,
    Caught,
    Undecided
};

int main() {
    int w, h;
    while(cin >> w >> h, w) {
        vector<string> v(h);
        for(auto& a : v) cin >> a;

        auto can_move_to = [&] (int y, int x) {
            return 0 <= y && y < h && 0 <= x && x < w && v[y][x] != '#';
        };

        int qy = -1, qx = -1, ay = -1, ax = -1;
        auto dp = table(h, w, h, w, 2, Undecided);
        auto deg = table(h, w, h, w, 2, 0);
        queue<tuple<int, int, int, int, int>> que;
        for(int i = 0; i < h; ++i) {
            for(int j = 0; j < w; ++j) {
                if(v[i][j] == '#') continue;

                if(v[i][j] == 'Q') qy = i, qx = j;
                if(v[i][j] == 'A') ay = i, ax = j;
                for(int k = 0; k < h; ++k) {
                    for(int l = 0; l < w; ++l) {
                        if(v[k][l] == '#' || (k == i && l == j)) continue;

                        for(int d = 0; d < 5; ++d) {
                            const int ny1 = i + dy[d], nx1 = j + dx[d];
                            const int ny2 = k + dy[d], nx2 = l + dx[d];
                            deg[i][j][k][l][0] += can_move_to(ny1, nx1) && v[i][j] != 'E';
                            deg[i][j][k][l][1] += can_move_to(ny2, nx2);
                        }

                        if(v[i][j] == 'E') {
                            dp[i][j][k][l][0] = Escape;
                            deg[i][j][k][l][0] = 0;
                            que.emplace(i, j, k, l, 0);
                        }
                    }
                }
                dp[i][j][i][j][0] = dp[i][j][i][j][1] = Caught;
                que.emplace(i, j, i, j, 0);
                que.emplace(i, j, i, j, 1);
            }
        }
        while(!que.empty()) {
            int qy, qx, ay, ax, turn; tie(qy, qx, ay, ax, turn) = que.front();
            que.pop();
            if(turn == 0) { // Queen's turn, so consider army's move
                for(int d = 0; d < 5; ++d) {
                    const int nay = ay + dy[d], nax = ax + dx[d];
                    if(!can_move_to(nay, nax) || dp[qy][qx][nay][nax][!turn] != Undecided) continue;
                    if(dp[qy][qx][ay][ax][turn] == Escape) {
                        if(--deg[qy][qx][nay][nax][!turn] == 0) {
                            dp[qy][qx][nay][nax][!turn] = Escape;
                            que.emplace(qy, qx, nay, nax, !turn);
                        }
                    } else {
                        deg[qy][qx][nay][nax][!turn] = 0;
                        dp[qy][qx][nay][nax][!turn] = Caught;
                        que.emplace(qy, qx, nay, nax, !turn);
                    }
                }
            } else {
                for(int d = 0; d < 5; ++d) {
                    const int nqy = qy + dy[d], nqx = qx + dx[d];
                    if(!can_move_to(nqy, nqx) || dp[nqy][nqx][ay][ax][!turn] != Undecided) continue;
                    if(dp[qy][qx][ay][ax][turn] == Escape) {
                        deg[nqy][nqx][ay][ax][!turn] = 0;
                        dp[nqy][nqx][ay][ax][!turn] = Escape;
                        que.emplace(nqy, nqx, ay, ax, !turn);
                    } else {
                        if(--deg[nqy][nqx][ay][ax][!turn] == 0) {
                            dp[nqy][nqx][ay][ax][!turn] = Caught;
                            que.emplace(nqy, nqx, ay, ax, !turn);
                        }
                    }
                }
            }
        }

        const auto ans = dp[qy][qx][ay][ax][0];
        if(ans == Escape) {
            cout << "Queen can escape." << endl;
        } else if(ans == Caught) {
            cout << "Army can catch Queen." << endl;
        } else {
            cout << "Queen can not escape and Army can not catch Queen." << endl;
        }
    }
}
accuracy: 1
time_ms: 420
memory_kb: 50372
final_rank: 15

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i))
#define all(x) (x).begin(),(x).end()
#define pb push_back
#define fi first
#define se second
#define dbg(x) cout<<#x" = "<<((x))<<endl
template<class T,class U> ostream& operator<<(ostream& o, const pair<T,U> &p){o<<"("<<p.fi<<","<<p.se<<")";return o;}
template<class T> ostream& operator<<(ostream& o, const vector<T> &v){o<<"[";for(T t:v){o<<t<<",";}o<<"]";return o;}

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

int h,w;
string s[N];

bool IN(int y, int x){
    return 0<=y && y<h && 0<=x && x<w && s[y][x]!='#';
}

int dp[N][N][N][N];

using pi = pair<int,int>;
using P = pair<pi,pi>;

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

        int qy,qx,ay,ax;
        rep(i,h)rep(j,w){
            if(s[i][j]=='Q'){
                qy = i;
                qx = j;
            }
            if(s[i][j]=='A'){
                ay = i;
                ax = j;
            }
        }

        memset(dp,-1,sizeof(dp));
        queue<P> que;

        // win
        rep(i,h)rep(j,w){
            if(s[i][j] != 'E') continue;
            rep(ii,h)rep(jj,w){
                int d = abs(i-ii) + abs(j-jj);
                if(d>0){
                    dp[i][j][ii][jj] = 1;
                    que.push({{i,j},{ii,jj}});
                }
            }
        }
        while(!que.empty()){
            P state = que.front();
            que.pop();
            pi queen = state.fi, army = state.se;
            // dbg(state);

            vector<P> check;
            rep(qd,5)rep(ad,5){
                int nqy = queen.fi + dy[qd];
                int nqx = queen.se + dx[qd];
                int nay = army.fi + dy[ad];
                int nax = army.se + dx[ad];
                if(!IN(nqy,nqx) || !IN(nay,nax) || dp[nqy][nqx][nay][nax]!=-1) continue;

                check.pb({{nqy,nqx},{nay,nax}});
            }

            for(const auto &ppp:check){
                pi nq = ppp.fi, na = ppp.se;

                int res = 0;
                rep(qd,5){
                    int nqy = nq.fi+dy[qd], nqx = nq.se+dx[qd];
                    if(!IN(nqy,nqx)) continue;

                    int tmp = 1;
                    rep(ad,5){
                        int nay = na.fi+dy[ad], nax = na.se+dx[ad];
                        if(!IN(nay,nax)) continue;
                        if(dp[nqy][nqx][nay][nax] != 1) tmp = 0;
                    }
                    if(tmp){
                        res = 1;
                        break;
                    }
                }

                if(res == 1){
                    dp[nq.fi][nq.se][na.fi][na.se] = 1;
                    que.push({nq,na});
                }
            }
        }

        // lose
        rep(i,h)rep(j,w){
            dp[i][j][i][j] = 0;
            que.push({{i,j},{i,j}});
        }
        while(!que.empty()){
            P state = que.front();
            que.pop();
            pi queen = state.fi, army = state.se;
            // dbg(state);

            vector<P> check;
            rep(qd,5)rep(ad,5){
                int nqy = queen.fi + dy[qd];
                int nqx = queen.se + dx[qd];
                int nay = army.fi + dy[ad];
                int nax = army.se + dx[ad];
                if(!IN(nqy,nqx) || !IN(nay,nax) || dp[nqy][nqx][nay][nax]!=-1) continue;

                check.pb({{nqy,nqx},{nay,nax}});
            }

            for(const auto &ppp:check){
                pi nq = ppp.fi, na = ppp.se;

                int res = 0;
                rep(qd,5){
                    int nqy = nq.fi+dy[qd], nqx = nq.se+dx[qd];
                    if(!IN(nqy,nqx)) continue;

                    int tmp = 1;
                    rep(ad,5){
                        int nay = na.fi+dy[ad], nax = na.se+dx[ad];
                        if(!IN(nay,nax)) continue;
                        if(dp[nqy][nqx][nay][nax] == 0){
                            tmp = 0;
                            break;
                        }
                    }

                    res |= tmp;
                }

                if(res == 0){
                    dp[nq.fi][nq.se][na.fi][na.se] = 0;
                    que.push({nq,na});
                }
            }
        }

        int res = dp[qy][qx][ay][ax];
        if(res == 0) printf("Army can catch Queen.\n");
        else if(res == 1) printf("Queen can escape.\n");
        else printf("Queen can not escape and Army can not catch Queen.\n");
    }
    return 0;
}
accuracy: 1
time_ms: 40
memory_kb: 6184
final_rank: 3

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

typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll> P;

#define fi first
#define se second
#define repl(i,a,b) for(int i=(int)(a);i<(int)(b);i++)
#define rep(i,n) repl(i,0,n)
#define all(x) (x).begin(),(x).end()
#define dbg(x) cout<<#x"="<<x<<endl
#define mmax(x,y) (x>y?x:y)
#define mmin(x,y) (x<y?x:y)
#define maxch(x,y) x=mmax(x,y)
#define minch(x,y) x=mmin(x,y)
#define uni(x) x.erase(unique(all(x)),x.end())
#define exist(x,y) (find(all(x),y)!=x.end())
#define bcnt __builtin_popcountll

#define INF 1e16
#define mod 1000000007

int W,H;
string s[33];
int ai,aj,qi,qj;
int st[33][33][33][33][2];
int rest[33][33][33][33][2];
int dd[]={-1,0,0,1,0,-1};

struct state{
  int qi,qj,ai,aj,t;
};

int main(){
  cin.tie(0);
  ios::sync_with_stdio(false);

  while(1){
    cin>>W>>H;
    if(W==0)break;
    rep(i,H){
      cin>>s[i];
      rep(j,W){
        if(s[i][j]=='A'){
          ai=i; aj=j;
        }
        if(s[i][j]=='Q'){
          qi=i; qj=j;
        }
      }
    }
    memset(st,-1,sizeof(st));
    memset(rest,0,sizeof(rest));
    queue<state> que;
    rep(sqi,H)rep(sqj,W)rep(sai,H)rep(saj,W)rep(tt,2){
      if(s[sqi][sqj]=='#'||s[sai][saj]=='#')continue;

      if(s[sqi][sqj]=='E'&&!(sqi==sai&&sqj==saj)&&tt==0){
        que.push((state){sqi,sqj,sai,saj,tt});
        st[sqi][sqj][sai][saj][tt]=1;
      }else if(sqi==sai&&sqj==saj){
        que.push((state){sqi,sqj,sai,saj,tt});
        st[sqi][sqj][sai][saj][tt]=0;
      }else if(tt==0){
        rep(d,5){
          int nqi=sqi+dd[d],nqj=sqj+dd[d+1];
          if(nqi<0||nqi>=H||nqj<0||nqj>=W||s[nqi][nqj]=='#')continue;
          rest[sqi][sqj][sai][saj][tt]++;
        }
      }else if(tt==1){
        rep(d,5){
          int nai=sai+dd[d],naj=saj+dd[d+1];
          if(nai<0||nai>=H||naj<0||naj>=W||s[nai][naj]=='#')continue;
          rest[sqi][sqj][sai][saj][tt]++;
        }
      }
    }

    while(que.size()){
      state c=que.front(); que.pop();
      int crtst=st[c.qi][c.qj][c.ai][c.aj][c.t];
      if(c.t==1){
        rep(d,5){
          int nqi=c.qi+dd[d],nqj=c.qj+dd[d+1];
          if(nqi<0||nqi>=H||nqj<0||nqj>=W||s[nqi][nqj]=='#'||
            st[nqi][nqj][c.ai][c.aj][1-c.t]!=-1)continue;
            if(crtst==1){
              que.push((state){nqi,nqj,c.ai,c.aj,1-c.t});
              st[nqi][nqj][c.ai][c.aj][1-c.t]=1;
              continue;
            }
            rest[nqi][nqj][c.ai][c.aj][1-c.t]--;
            if(rest[nqi][nqj][c.ai][c.aj][1-c.t]==0){
              que.push((state){nqi,nqj,c.ai,c.aj,1-c.t});
              st[nqi][nqj][c.ai][c.aj][1-c.t]=0;
            }
          }
        }else if(c.t==0){
          rep(d,5){
            int nai=c.ai+dd[d],naj=c.aj+dd[d+1];
            if(nai<0||nai>=H||naj<0||naj>=W||s[nai][naj]=='#'||
              st[c.qi][c.qj][nai][naj][1-c.t]!=-1)continue;
              if(crtst==0){
                que.push((state){c.qi,c.qj,nai,naj,1-c.t});
                st[c.qi][c.qj][nai][naj][1-c.t]=0;
                continue;
              }
              rest[c.qi][c.qj][nai][naj][1-c.t]--;
              if(rest[c.qi][c.qj][nai][naj][1-c.t]==0){
                que.push((state){c.qi,c.qj,nai,naj,1-c.t});
                st[c.qi][c.qj][nai][naj][1-c.t]=1;
              }
            }
          }
        }

        if(st[qi][qj][ai][aj][0]==-1)cout<<"Queen can not escape and Army can not catch Queen."<<endl;
        if(st[qi][qj][ai][aj][0]==0) cout<<"Army can catch Queen."<<endl;
        if(st[qi][qj][ai][aj][0]==1) cout<<"Queen can escape."<<endl;
      }
      return 0;
    }
accuracy: 1
time_ms: 60
memory_kb: 21756
final_rank: 7

code_snippet: #include <bits/stdc++.h>
#define MOD 1000000007LL
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
typedef pair<P,P> PP;

class graph_bridge{
public:
	static const int MAX=905;
	vector<int> G[MAX];
	bool visited[MAX];
	int prenum[MAX],parent[MAX],lowest[MAX],timer;
	set<P> bridge;
	int cmp[MAX];

	void dfs(int v,int prev){
		prenum[v]=lowest[v]=timer;
		timer++;
		visited[v]=true;
		int next;
		for(int i=0;i<G[v].size();i++){
			next=G[v][i];
			if(!visited[next]){
				parent[next]=v;
				dfs(next,v);
				lowest[v]=min(lowest[v],lowest[next]);
				if(prenum[v]<lowest[G[v][i]])bridge.insert(P(min(v,G[v][i]),max(v,G[v][i])));
			}else if(next!=prev){
				lowest[v]=min(lowest[v],prenum[next]);
			}
		}
	}

	void dfs2(int v,int k){
		cmp[v]=k;
		for(int i=0;i<G[v].size();i++){
			int nv=G[v][i];
			if(cmp[nv]>=0)continue;
			if(bridge.find(P(min(v,nv),max(v,nv)))==bridge.end()){
				dfs2(nv,k);
			}
		}
	}

	int construct_TwoEdgeConnectedComponent(int N){
		for(int i=0;i<N;i++){
			visited[i]=false;
		}
		timer=1;
		bridge.clear();
		for(int i=0;i<N;i++){
			if(!visited[i]){
				dfs(i,-1);
			}
		}
		memset(cmp,-1,sizeof(cmp));
		int k=0;
		for(int i=0;i<N;i++){
			if(cmp[i]==-1){
				dfs2(i,k);
				k++;
			}
		}
		return k;
	}
};

graph_bridge b;

int w,h;
int fie[31][31];
bool flag[31][31][31][31];
int dx[5]={0,1,0,-1,0};
int dy[5]={1,0,-1,0,0};
int dist[2][31][31];
int cnt[905];
P q,a;

void bfs(){
	memset(dist,-1,sizeof(dist));
	for(int i=0;i<2;i++){
		queue<P> que;
		if(i==0){
			que.push(q);
			dist[i][q.first][q.second]=0;
		}else{
			que.push(a);
			dist[i][a.first][a.second]=0;
		}
		while(que.size()){
			P p=que.front();
			que.pop();
			for(int j=0;j<4;j++){
				int nx=p.second+dx[j];
				int ny=p.first+dy[j];
				if(nx<0 || ny<0 || nx>=w || ny>=h)continue;
				if(fie[ny][nx]==-1)continue;
				if(dist[i][ny][nx]==-1){
					dist[i][ny][nx]=dist[i][p.first][p.second]+1;
					que.push(P(ny,nx));
				}
			}
		}
	}
}

void solve(){
	memset(fie,0,sizeof(fie));
	memset(flag,false,sizeof(flag));
	memset(cnt,0,sizeof(cnt));
	for(int i=0;i<h;i++){
		string str;
		cin >> str;
		for(int j=0;j<w;j++){
			if(str[j]=='#'){
				fie[i][j]=-1;
			}
			if(str[j]=='E'){
				fie[i][j]=1;
			}
			if(str[j]=='Q'){
				q=P(i,j);
			}
			if(str[j]=='A'){
				a=P(i,j);
			}
		}
	}
	queue<PP> que;
	for(int i=0;i<h;i++){
		for(int j=0;j<w;j++){
			if(fie[i][j]==1){
				for(int k=0;k<h;k++){
					for(int l=0;l<w;l++){
						if(k==i && l==j)continue;
						if(fie[k][l]==-1)continue;
						flag[i][j][k][l]=true;
						que.push(PP(P(i,j),P(k,l)));
					}
				}
			}
		}
	}
	while(que.size()){
		PP p=que.front();
		que.pop();
		P pq=p.first,pa=p.second;
		//printf("%d %d %d %d\n",pq.second,pq.first,pa.second,pa.first);
		for(int i=0;i<4;i++){
			int nx=pq.second+dx[i];
			int ny=pq.first+dy[i];
			//printf("%d %d\n",nx,ny);
			if(nx<0 || ny<0 || nx>=w || ny>=h)continue;
			if(fie[ny][nx]==-1)continue;
			for(int j=0;j<5;j++){
				int n2x=pa.second+dx[j];
				int n2y=pa.first+dy[j];
				//printf("n2x %d %d\n",n2x,n2y);
				if(n2x<0 || n2y<0 || n2x>=w || n2y>=h)continue;
				if(fie[n2y][n2x]==-1)continue;
				if(nx==n2x && ny==n2y)continue;
				if(flag[ny][nx][n2y][n2x])continue;
				bool fo=true;
				for(int k=0;k<5;k++){
					int n3x=n2x+dx[k];
					int n3y=n2y+dy[k];
					//printf("check %d %d\n",n3x,n3y);
					if(n3x<0 || n3y<0 || n3x>=w || n3y>=h)continue;
					if(fie[n3y][n3x]==-1)continue;
					if(!flag[pq.first][pq.second][n3y][n3x])fo=false;
				}
				if(fo){
					//printf("ok %d %d %d %d\n",nx,ny,n2x,n2y);
					flag[ny][nx][n2y][n2x]=true;
					que.push(PP(P(ny,nx),P(n2y,n2x)));
				}
			}
		}
	}
	if(flag[q.first][q.second][a.first][a.second]){
		printf("Queen can escape.\n");
		return;
	}
	bfs();
	for(int i=0;i<h*w;i++){
		b.G[i].clear();
	}
	for(int i=0;i<h;i++){
		for(int j=0;j<w;j++){
			if(fie[i][j]>=0){
				for(int k=0;k<4;k++){
					int nx=j+dx[k];
					int ny=i+dy[k];
					if(nx<0 || nx>=w || ny<0 || ny>=h)continue;
					if(fie[ny][nx]==-1)continue;
					b.G[i*w+j].push_back(ny*w+nx);
				}
			}
		}
	}
	int sz=b.construct_TwoEdgeConnectedComponent(h*w);
	for(int i=0;i<h*w;i++){
		cnt[b.cmp[i]]++;
	}
	bool draw=false;
	for(int i=0;i<h;i++){
		for(int j=0;j<w;j++){
			//printf("%d %d %d\n",i,j,cnt[b.cmp[i*w+j]]);
			if(cnt[b.cmp[i*w+j]]>1 && dist[0][i][j]>=0 && (dist[0][i][j]<dist[1][i][j] || dist[1][i][j]==-1)){
				draw=true;
			}
		}
	}
	if(dist[1][q.first][q.second]==-1)draw=true;
	printf("%s\n",draw?"Queen can not escape and Army can not catch Queen.":"Army can catch Queen.");
	return;
}

int main(void){
	while(1){
		scanf("%d%d",&w,&h);
		if(w==0 && h==0)break;
		solve();
	}
}
accuracy: 1
time_ms: 10
memory_kb: 4228
final_rank: 1

code_snippet: #include<bits/stdc++.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define HUGE_NUM 99999999999999999
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;


#define NUM 31

enum Type{
	CAN_EXIT,
	CAUGHT,
	INFINITE_LOOP,
};

enum Which{
	turn_Queen,
	turn_Army,
};

struct LOC{
	void set(int arg_row,int arg_col){
		row = arg_row;
		col = arg_col;
	}
	int row,col;
};

struct Info{
	Info(){
		Q_row = 0;
		Q_col = 0;
		A_row = 0;
		A_col = 0;
	}
	Info(int arg_Q_row,int arg_Q_col,int arg_A_row,int arg_A_col){
		Q_row = arg_Q_row;
		Q_col = arg_Q_col;
		A_row = arg_A_row;
		A_col = arg_A_col;
	}
	int Q_row,Q_col,A_row,A_col;
};

int W,H;
int diff_row[5] = {-1,0,0,0,1},diff_col[5] = {0,-1,0,1,0};
LOC Q_start,A_start;
char base_map[NUM][NUM+1];
Type table[NUM][NUM][NUM][NUM][2];
queue<Info> QUEEN[2],ARMY[2];


bool rangeCheck(int row,int col){

	if(row >= 0 && row <= H-1 && col >= 0 && col <= W-1 && base_map[row][col] != '#'){

		return true;
	}else{
		return false;
	}
}

void init_dp(){

	for(int row = 0; row < H; row++){
		for(int col = 0; col < W; col++){
			for(int row2 = 0; row2 < H; row2++){
				for(int col2 = 0; col2 < W; col2++){
					table[row][col][row2][col2][turn_Queen] = INFINITE_LOOP;
					table[row][col][row2][col2][turn_Army] = INFINITE_LOOP;
				}
			}
		}
	}
}

void set_exit(int exit_row,int exit_col){

	for(int row = 0; row < H; row++){
		for(int col = 0; col < W; col++){
			table[exit_row][exit_col][row][col][turn_Queen] = CAN_EXIT;
		}
	}
}

void set_caught(){

	for(int row = 0; row < H; row++){
		for(int col = 0; col < W; col++){
			table[row][col][row][col][turn_Queen] = CAUGHT;
			table[row][col][row][col][turn_Army] = CAUGHT;
		}
	}
}

void func(){

	init_dp();

	for(int i = 0; i < 2; i++){
		while(!QUEEN[i].empty())QUEEN[i].pop();
		while(!ARMY[i].empty())ARMY[i].pop();
	}

	for(int row = 0; row < H; row++){

		scanf("%s",base_map[row]);

		for(int col = 0; col < W; col++){

			if(base_map[row][col] == 'Q'){

				Q_start.set(row,col);

			}else if(base_map[row][col] == 'A'){

				A_start.set(row,col);

			}else if(base_map[row][col] == 'E'){

				set_exit(row,col);
			}
		}
	}

	set_caught();

	for(int row = 0; row < H; row++){
		for(int col = 0; col < W; col++){
			for(int row2 = 0; row2 < H; row2++){
				for(int col2 = 0; col2 < W; col2++){
					if(table[row][col][row2][col2][turn_Queen] == INFINITE_LOOP){
						QUEEN[0].push(Info(row,col,row2,col2));
					}
					if(table[row][col][row2][col2][turn_Army] == INFINITE_LOOP){
						ARMY[0].push(Info(row,col,row2,col2));
					}
				}
			}
		}
	}

	bool FLG;
	int CURRENT = 0,NEXT = 1;
	Info info;
	int adj_row,adj_col;
	bool exit_FLG,caught_FLG;

	while(true){

		FLG = false;

		while(!QUEEN[CURRENT].empty()){

			info = QUEEN[CURRENT].front();
			QUEEN[CURRENT].pop();

			if(table[info.Q_row][info.Q_col][info.A_row][info.A_col][turn_Queen] != INFINITE_LOOP){
				continue;
			}
			exit_FLG = false;
			caught_FLG = true;

			for(int i = 0; i < 5; i++){

				adj_row = info.Q_row+diff_row[i];
				adj_col = info.Q_col+diff_col[i];

				if(!rangeCheck(adj_row,adj_col))continue;

				if(table[adj_row][adj_col][info.A_row][info.A_col][turn_Army] == CAN_EXIT){
					exit_FLG = true;
				}

				if(table[adj_row][adj_col][info.A_row][info.A_col][turn_Army] != CAUGHT){
					caught_FLG = false;
				}
			}

			if(exit_FLG){
				table[info.Q_row][info.Q_col][info.A_row][info.A_col][turn_Queen] = CAN_EXIT;
				FLG = true;
			}

			if(caught_FLG){
				table[info.Q_row][info.Q_col][info.A_row][info.A_col][turn_Queen] = CAUGHT;
				FLG = true;
			}

			if(exit_FLG == false && caught_FLG == false){
				QUEEN[NEXT].push(info);
			}
		}

		while(!ARMY[CURRENT].empty()){

			info = ARMY[CURRENT].front();
			ARMY[CURRENT].pop();

			if(table[info.Q_row][info.Q_col][info.A_row][info.A_col][turn_Army] != INFINITE_LOOP){
				continue;
			}
			exit_FLG = true;
			caught_FLG = false;

			for(int i = 0; i < 5; i++){

				adj_row = info.A_row+diff_row[i];
				adj_col = info.A_col+diff_col[i];

				if(!rangeCheck(adj_row,adj_col))continue;

				if(table[info.Q_row][info.Q_col][adj_row][adj_col][turn_Queen] == CAUGHT){
					caught_FLG = true;
				}

				if(table[info.Q_row][info.Q_col][adj_row][adj_col][turn_Queen] != CAN_EXIT){
					exit_FLG = false;
				}
			}

			if(exit_FLG){
				table[info.Q_row][info.Q_col][info.A_row][info.A_col][turn_Army] = CAN_EXIT;
				FLG = true;
			}

			if(caught_FLG){
				table[info.Q_row][info.Q_col][info.A_row][info.A_col][turn_Army] = CAUGHT;
				FLG = true;
			}

			if(exit_FLG == false && caught_FLG == false){
				ARMY[NEXT].push(info);
			}
		}

		if(!FLG)break;

		swap(CURRENT,NEXT);
	}

	switch(table[Q_start.row][Q_start.col][A_start.row][A_start.col][turn_Queen]){
	case CAN_EXIT:
		printf("Queen can escape.\n");
		break;
	case CAUGHT:
		printf("Army can catch Queen.\n");
		break;
	case INFINITE_LOOP:
		printf("Queen can not escape and Army can not catch Queen.\n");
		break;
	}
}

int main(){

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

		func();
	}

	return 0;
}
accuracy: 1
time_ms: 740
memory_kb: 22572
final_rank: 11

code_snippet: #include <bits/stdc++.h>
#define GET_MACRO(_1,_2,_3,_4,_5,_6,NAME,...) NAME
#define pr(...) GET_MACRO(__VA_ARGS__,pr6,pr5,pr4,pr3,pr2,pr1)(__VA_ARGS__)
#define Pr(a) (#a)<<"="<<(a)<<" "
#define pr1(a) cerr<<Pr(a)<<endl
#define pr2(a,b) cerr<<Pr(a)<<Pr(b)<<endl
#define pr3(a,b,c) cerr<<Pr(a)<<Pr(b)<<Pr(c)<<endl
#define pr4(a,b,c,d) cerr<<Pr(a)<<Pr(b)<<Pr(c)<<Pr(d)<<endl
#define pr5(a,b,c,d,e) cerr<<Pr(a)<<Pr(b)<<Pr(c)<<Pr(d)<<Pr(e)<<endl
#define pr6(a,b,c,d,e,f) cerr<<Pr(a)<<Pr(b)<<Pr(c)<<Pr(d)<<Pr(e)<<Pr(f)<<endl
#define int long long
#define double long double
using namespace std;
const int INF = 1LL<<55;
const int mod = (1e9)+7;
const double EPS = 1e-8;
const double PI = 6.0 * asin(0.5);
typedef pair<int,int> P;
typedef long long ll;
template<class T> T Max(T &a,T b){return a=max(a,b);}
template<class T> T Min(T &a,T b){return a=min(a,b);}
ostream& operator<<(ostream& o,P p){return o<<"("<<p.first<<","<<p.second<<")";}
istream& operator>>(istream& i,P &p){return i>>p.first>>p.second;}
ostream& operator<<(ostream& o,vector<auto> &a){int i=0;for(auto t:a)o<<(i++?" ":"")<<t;return o;}
istream& operator>>(istream& i,vector<auto> &a){for(auto &t:a)i>>t;return i;}
void prArr(auto a,string s=" "){int i=0;for(auto t:a)cout<<(i++?s:"")<<t;cout<<endl;}
const int N = 31;

int h, w;
vector<string> mp;
int dx[] = {0, 0, 0, 1, -1};
int dy[] = {0, 1, -1, 0, 0};
int in(int x,int y){return 0 <= x && x < w && 0 <= y && y < h;}
int canMove(int x,int y){return in(x, y) && mp[y][x] != '#';}

int dp[2][N][N][N][N];
int used[2][N][N][N][N];
int cnt[2][N][N][N][N];
int bfs(){

  struct dat{
    int turn;
    int y, x;
    int b, a;
    dat();
    dat(int turn,int y,int x,int b,int a):turn(turn), y(y), x(x), b(b), a(a){}
  };
  
  memset(dp,-1,sizeof(dp));
  memset(used,0,sizeof(used));
  memset(cnt,0,sizeof(cnt));

  int Qx, Qy, Ax, Ay;
  for(int i=0;i<h;i++)
    for(int j=0;j<w;j++){
      if(mp[i][j] == 'Q') Qx = j, Qy = i;
      if(mp[i][j] == 'A') Ax = j, Ay = i;
    }
  
  queue<dat> Q;
  
  // dp[0]->Q's turn
  // dp[1]->A's turn

  for(int i=0;i<h;i++)
    for(int j=0;j<w;j++)
      for(int b=0;b<h;b++)
        for(int a=0;a<w;a++){
          if(mp[i][j] == '#' || mp[b][a] == '#') continue;
	  
          //Qの勝ち確定
          if((i != b || j != a) && mp[i][j] == 'E') {
            Q.push(dat(0, i, j, b, a));
            dp[0][i][j][b][a] = 1;
            used[0][i][j][b][a] = 1;
          }
          
          //Aの勝ち確定
          if(i == b && j == a) {
	    
	    //Qの負け
	    {
	      Q.push(dat(0, i, j, b, a));	    
	      dp[0][i][j][b][a] = 0;
	      used[0][i][j][b][a] = 1;
	    }
	    
	    for(int k=0;k<5;k++){
              int nb = b + dy[k];
              int na = a + dx[k];
              if(!canMove(na, nb) || used[1][i][j][nb][na]) continue;
	      Q.push(dat(1, i, j, nb, na));
	      dp[1][i][j][nb][na] = 1;
	      used[1][i][j][nb][na] = 1;
	    }
	  }
	}

  
  auto getVal=[&](int turn, int y,int x,int b,int a){
    int draw = 0;
    for(int i=0;i<5;i++){
      int nturn = !turn;
      int ny = y + (turn == 0? dy[i]:0);
      int nx = x + (turn == 0? dx[i]:0);
      int nb = b + (turn == 1? dy[i]:0);
      int na = a + (turn == 1? dx[i]:0);
      if(!canMove(nx, ny) || !canMove(na, nb)) continue;
      if(dp[nturn][ny][nx][nb][na] == 0) return 1LL;
      if(dp[nturn][ny][nx][nb][na] == -1) draw = 1;
    }
    return draw? -1LL:0LL;
  };
  
  while(!Q.empty()){
    auto t = Q.front(); Q.pop();
    int turn = t.turn;
    int y = t.y, x = t.x;
    int b = t.b, a = t.a;
    
    for(int i=0;i<5;i++){
      int nturn = !turn;
      int ny = y + (nturn == 0? dy[i]:0);
      int nx = x + (nturn == 0? dx[i]:0);
      int nb = b + (nturn == 1? dy[i]:0);
      int na = a + (nturn == 1? dx[i]:0);
      if(!canMove(nx,ny) || !canMove(na,nb)) continue;
      if(used[nturn][ny][nx][nb][na]) continue; 
      
      int nval = getVal(nturn, ny, nx, nb, na);
      if(nval == -1) continue;
      dp[nturn][ny][nx][nb][na] = nval;
      Q.push(dat(nturn, ny, nx, nb, na));
      used[nturn][ny][nx][nb][na] = 1;
    }
  }

  return dp[0][Qy][Qx][Ay][Ax];
}


signed main(){
  cin.tie(0);
  ios_base::sync_with_stdio(0);
  cout << fixed << setprecision(12);

  while(1){
    
    cin>>w>>h;
    if(w == 0 && h == 0) return 0;
    mp.clear();
    mp.resize(h);
    cin>>mp;

    int ans = bfs();
    if(ans == -1) cout<<"Queen can not escape and Army can not catch Queen."<<endl;
    if(ans == 0) cout<<"Army can catch Queen."<<endl;
    if(ans == 1) cout<<"Queen can escape."<<endl;
  }
  return 0;
}
accuracy: 1
time_ms: 170
memory_kb: 46328
final_rank: 14

code_snippet: #include<bits/stdc++.h>
using namespace std;
using Int = long long;
Int dp[2][33][33][33][33];
Int cnt[2][33][33][33][33];
signed main(){  
  cin.tie(0);
  ios::sync_with_stdio(0);
  Int w,h;
  while(cin>>w>>h,w){
    vector<string> s(h);
    for(Int i=0;i<h;i++) cin>>s[i];
    memset(dp,-1,sizeof(dp));
    memset(cnt,0,sizeof(cnt));
    {
      using T = tuple<Int, Int, Int, Int, Int>;
      queue<T> q;
      Int dy[]={0,0,1,-1,0};
      Int dx[]={1,-1,0,0,0};
      auto in=[&](Int y,Int x){
	return 0<=y&&y<h&&0<=x&&x<w;
      };
      
      for(Int qy=0;qy<h;qy++){
	for(Int qx=0;qx<w;qx++){
	  if(s[qy][qx]=='#') continue;
	  for(Int ay=0;ay<h;ay++){
	    for(Int ax=0;ax<w;ax++){
	      if(s[ay][ax]=='#') continue;
	      // t == 0	      
	      {		
		if(s[qy][qx]=='E'&&!(qy==ay&&qx==ax)){
		  dp[0][qy][qx][ay][ax]=1;
		  q.emplace(0,qy,qx,ay,ax);
		}
		for(Int k=0;k<5;k++){
		  Int ny=qy+dy[k],nx=qx+dx[k];
		  if(!in(ny,nx)||s[ny][nx]=='#') continue;
		  cnt[0][qy][qx][ay][ax]++;
		}
	      }
	      // t == 1
	      {
		for(Int k=0;k<5;k++){
		  Int ny=ay+dy[k],nx=ax+dx[k];
		  if(!in(ny,nx)||s[ny][nx]=='#') continue;
		  if(ny==qy&&nx==qx){		    
		    dp[1][qy][qx][ay][ax]=1;
		    q.emplace(1,qy,qx,ay,ax);		  
		  }
		  cnt[1][qy][qx][ay][ax]++;
		}
	      }
	    }
	  }	
	}
      }
      //cout<<cnt[0][0][0][0][1]<<endl;
      const Int DBG = 0;
      
      while(!q.empty()){
	Int t,qy,qx,ay,ax;
	tie(t,qy,qx,ay,ax)=q.front();q.pop();
	Int d=dp[t][qy][qx][ay][ax];
	if(DBG) cout<<t<<":"<<qy<<" "<<qx<<" "<<ay<<" "<<ax<<":"<<d<<endl;
	
	if(t){
	  for(Int k=0;k<5;k++){
	    Int ny=qy+dy[k],nx=qx+dx[k];
	    if(!in(ny,nx)||s[ny][nx]=='#') continue;
	    if(~dp[!t][ny][nx][ay][ax]) continue;
	    cnt[!t][ny][nx][ay][ax]--;
	    if(!d||cnt[!t][ny][nx][ay][ax]==0){
	      if(DBG) cout<<"->"<<!t<<" "<<ny<<" "<<nx<<" "<<ay<<" "<<ax<<":"<<!d<<endl;
	      dp[!t][ny][nx][ay][ax]=!d;
	      q.emplace(!t,ny,nx,ay,ax);
	    }
	  }
	}else{
	  for(Int k=0;k<5;k++){
	    Int ny=ay+dy[k],nx=ax+dx[k];
	    if(!in(ny,nx)||s[ny][nx]=='#') continue;
	    if(~dp[!t][qy][qx][ny][nx]) continue;
	    cnt[!t][qy][qx][ny][nx]--;
	    if(!d||cnt[!t][qy][qx][ny][nx]==0){
	      if(DBG) cout<<"->"<<!t<<" "<<qy<<" "<<qx<<" "<<ny<<" "<<nx<<":"<<!d<<endl;
	      dp[!t][qy][qx][ny][nx]=!d;
	      q.emplace(!t,qy,qx,ny,nx);
	    }
	  }
	}
      }
      
    }
    
    
    {
      Int qx,qy,ax,ay;
      for(Int i=0;i<h;i++){
	for(Int j=0;j<w;j++){
	  if(s[i][j]=='Q') qy=i,qx=j;
	  if(s[i][j]=='A') ay=i,ax=j;
	}
      }
      if(dp[0][qy][qx][ay][ax]==1)
	cout<<"Queen can escape."<<endl;
      if(dp[0][qy][qx][ay][ax]==0)
	cout<<"Army can catch Queen."<<endl;
      if(dp[0][qy][qx][ay][ax]==-1)
	cout<<"Queen can not escape and Army can not catch Queen."<<endl;
    }
  }
  
  return 0;
}
accuracy: 1
time_ms: 130
memory_kb: 40268
final_rank: 13

code_snippet: #include<bits/stdc++.h>
using namespace std;
using Int = long long;
Int dp[2][33][33][33][33];
Int cnt[2][33][33][33][33];
signed main(){  
  cin.tie(0);
  ios::sync_with_stdio(0);
  Int w,h;
  while(cin>>w>>h,w){
    vector<string> s(h);
    for(Int i=0;i<h;i++) cin>>s[i];
    memset(dp,-1,sizeof(dp));
    memset(cnt,0,sizeof(cnt));
    {
      using T = tuple<Int, Int, Int, Int, Int>;
      queue<T> q;
      Int dy[]={0,0,1,-1,0};
      Int dx[]={1,-1,0,0,0};
      auto in=[&](Int y,Int x){
	return 0<=y&&y<h&&0<=x&&x<w;
      };
      
      for(Int qy=0;qy<h;qy++){
	for(Int qx=0;qx<w;qx++){
	  if(s[qy][qx]=='#') continue;
	  for(Int ay=0;ay<h;ay++){
	    for(Int ax=0;ax<w;ax++){
	      if(s[ay][ax]=='#') continue;
	      // t == 0	      
	      {		
		if(s[qy][qx]=='E'&&!(qy==ay&&qx==ax)){
		  dp[0][qy][qx][ay][ax]=1;
		  q.emplace(0,qy,qx,ay,ax);
		}
		for(Int k=0;k<5;k++){
		  Int ny=qy+dy[k],nx=qx+dx[k];
		  if(!in(ny,nx)||s[ny][nx]=='#') continue;
		  cnt[0][qy][qx][ay][ax]++;
		}
	      }
	      // t == 1
	      {
		for(Int k=0;k<5;k++){
		  Int ny=ay+dy[k],nx=ax+dx[k];
		  if(!in(ny,nx)||s[ny][nx]=='#') continue;
		  if(ny==qy&&nx==qx){		    
		    dp[1][qy][qx][ay][ax]=1;
		    q.emplace(1,qy,qx,ay,ax);		  
		  }
		  cnt[1][qy][qx][ay][ax]++;
		}
	      }
	    }
	  }	
	}
      }
      //cout<<cnt[0][0][0][0][1]<<endl;
      const Int DBG = 0;
      
      while(!q.empty()){
	Int t,qy,qx,ay,ax;
	tie(t,qy,qx,ay,ax)=q.front();q.pop();
	Int d=dp[t][qy][qx][ay][ax];
	if(DBG) cout<<t<<":"<<qy<<" "<<qx<<" "<<ay<<" "<<ax<<":"<<d<<endl;
	
	if(t){
	  for(Int k=0;k<5;k++){
	    Int ny=qy+dy[k],nx=qx+dx[k];
	    if(!in(ny,nx)||s[ny][nx]=='#') continue;
	    if(~dp[!t][ny][nx][ay][ax]) continue;
	    cnt[!t][ny][nx][ay][ax]--;
	    if(!d||cnt[!t][ny][nx][ay][ax]==0){
	      if(DBG) cout<<"->"<<!t<<" "<<ny<<" "<<nx<<" "<<ay<<" "<<ax<<":"<<!d<<endl;
	      dp[!t][ny][nx][ay][ax]=!d;
	      q.emplace(!t,ny,nx,ay,ax);
	    }
	  }
	}else{
	  for(Int k=0;k<5;k++){
	    Int ny=ay+dy[k],nx=ax+dx[k];
	    if(!in(ny,nx)||s[ny][nx]=='#') continue;
	    if(~dp[!t][qy][qx][ny][nx]) continue;
	    cnt[!t][qy][qx][ny][nx]--;
	    if(!d||cnt[!t][qy][qx][ny][nx]==0){
	      if(DBG) cout<<"->"<<!t<<" "<<qy<<" "<<qx<<" "<<ny<<" "<<nx<<":"<<!d<<endl;
	      dp[!t][qy][qx][ny][nx]=!d;
	      q.emplace(!t,qy,qx,ny,nx);
	    }
	  }
	}
      }
      
    }
    
    
    {
      Int qx,qy,ax,ay;
      for(Int i=0;i<h;i++){
	for(Int j=0;j<w;j++){
	  if(s[i][j]=='Q') qy=i,qx=j;
	  if(s[i][j]=='A') ay=i,ax=j;
	}
      }
      if(dp[0][qy][qx][ay][ax]==1)
	cout<<"Queen can escape."<<endl;
      if(dp[0][qy][qx][ay][ax]==0)
	cout<<"Army can catch Queen."<<endl;
      if(dp[0][qy][qx][ay][ax]==-1)
	cout<<"Queen can not escape and Army can not catch Queen."<<endl;
    }
  }
  
  return 0;
}
accuracy: 1
time_ms: 130
memory_kb: 40116
final_rank: 12

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

typedef vector<vector<int>> Graph;

vector<int> solve(const Graph&g) {
	vector<int>nums(g.size());
	map<int, vector<int>> revg;
	for (int i = 0; i < g.size();++i){
		auto es(g[i]);
		nums[i] = es.size();
		for (auto e : es) {
			revg[e].push_back(i);
		}

	}

	//1 : win   0 : draw   -1 :loss
	vector<int>anss(g.size());
	queue<int>que;
	for (int i = 0; i < g.size(); ++i) {
		if (!nums[i]) {
			que.push(i);
			anss[i] = -1;
		}
	}
	while (!que.empty()) {
		int now(que.front());
		que.pop();
		if (anss[now] == 1) {
			for (auto reve : revg[now]) {
				nums[reve]--;
				if (!nums[reve]&&anss[reve]==0) {
					anss[reve] = -1;
					que.push(reve);
				}
			}
		}
		else if (anss[now] == -1) {
			if (revg.find(now)!=revg.end()) {
				for (auto reve : revg[now]) {
					if (anss[reve] == 0) {
						anss[reve] = 1;
						que.push(reve);
					}
				}
			}
			
		}
		else {
			assert(false);
		}
	}
	return anss;
}
int SIZE = 30;
int gethash(int ax, int ay, int bx, int by, int c) {
	return (ax-1)* SIZE * SIZE * SIZE * 2 + (ay-1)* SIZE * SIZE * 2 + (bx-1) * SIZE * 2 + (by-1) * 2 + c+1;
}

int main() {
	while (true) {
		int W, H; cin >> W >> H;
		if (!W)break;
		vector<vector<int>>field(H + 2, vector<int>(W + 2,-1));
		int sqx, sqy, sax, say;
		for (int i = 0; i < H; ++i) {
			string st; cin >> st;
			for (int j = 0; j < W; ++j) {
				switch (st[j]) {
				case 'Q':
					field[i + 1][j + 1] = 0;
					sqx = j + 1; sqy = i + 1;
					break;
				case 'A':
					field[i + 1][j + 1] = 0;
					sax = j + 1; say = i + 1;
					break;
				case '#':
					break;
				case '.':
					field[i + 1][j + 1] = 0;
					break;
				case 'E':
					field[i + 1][j + 1] = 2;
					break;
				default:
					assert(false);
				}
			}
		}
		SIZE = max(H, W);
		Graph g(SIZE * SIZE * SIZE*SIZE*2+1);
		int dx[] = { -1,0,1,0,0 };
		int dy[] = { 0,1,0,-1,0 };
		for (int qx = 1; qx < W + 1; ++qx) {
			for (int qy = 1; qy < H + 1; ++qy) {
				if (field[qy][qx] == -1)continue;
				for (int ax = 1; ax < W + 1; ++ax) {
					for (int ay = 1; ay < H + 1; ++ay) {
						if (field[ay][ax] == -1)continue;
						for (int nt = 0; nt < 2; ++nt) {
							int nowhash = gethash(qx, qy, ax, ay, nt);
							if (qx == ax&&qy == ay) {
								if (nt) {
									continue;
								}
								else {
									g[nowhash].push_back(0);
								}
							}
							if (field[qy][qx] == 2&&nt) {
								g[nowhash].push_back(0);
							}
							for (int way = 0; way < 5; ++way) {
								int nqx(qx), nqy(qy), nax(ax), nay(ay);
								if (nt) {
									nqx += dx[way]; nqy += dy[way];
									if (field[nqy][nqx]==-1) continue;
								}
								else {
									nax += dx[way]; nay += dy[way];
									if ((field[nay][nax]==-1)) continue;
								}
								if (nax == nqx&&nay == nqy) {
									if (nt) {
										continue;
									}
									else {
										g[nowhash].push_back(0);
									}
								}
								int nexthash = gethash(nqx, nqy, nax, nay, !nt);
								g[nowhash].push_back(nexthash);

							}
						}
					}
				}
			}
		}
		auto anss=solve(g);
		int ans = anss[gethash(sqx, sqy, sax, say, 1)];
		if (ans == 0)cout << "Queen can not escape and Army can not catch Queen." << endl;
		else if (ans == 1)cout << "Queen can escape." << endl;
		else cout << "Army can catch Queen." << endl;
	}

	
	return 0;
}
accuracy: 1
time_ms: 710
memory_kb: 61444
final_rank: 17

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define FOR(i,k,n) for(int i = (int)(k); i < (int)(n); i++)
#define REP(i,n) FOR(i,0,n)
#define ALL(a) a.begin(), a.end()
#define MS(m,v) memset(m,v,sizeof(m))
typedef long long ll;
typedef long double ld;
typedef vector<int> vi;
typedef vector<string> vs;
typedef pair<int, int> pii;
const int MOD = 1000000007;
const int INF = MOD + 1;
const ld EPS = 1e-12;
template<class T> T &chmin(T &a, const T &b) { return a = min(a, b); }
template<class T> T &chmax(T &a, const T &b) { return a = max(a, b); }

/*--------------------template--------------------*/
const int dx[] = { -1, 0, 0, 1 }, dy[] = { 0, -1, 1, 0 };
//[const int dx[] = { -1, -1, -1, 0, 0, 1, 1, 1 }, dy[] = { 0, -1, 1, -1, 1, 0, -1, 1 };
bool valid(int x, int y, int h, int w) { return (x >= 0 && y >= 0 && x < h&&y < w); }
int place(int x, int y, int w) { return w*x + y; }

int dp[2][33][33][33][33]; //turn, x_queen, y_queen, x_army, y_army
int h, w;
vs fld;

typedef tuple<int, int, int, int, int> state;

void init()
{
	fld.clear(); fld.resize(h);
	MS(dp, 0);
}

int main()
{
	cin.sync_with_stdio(false); cout << fixed << setprecision(10);
	while (cin >> w >> h, h)
	{
		init();
		REP(i, h) cin >> fld[i];
		pii army, queen;
		set<pii> exit;
		REP(i, h)REP(j, w)
		{
			if (fld[i][j] == '#') continue;
			if (fld[i][j] == 'Q') queen = pii(i, j);
			if (fld[i][j] == 'A') army = pii(i, j);
			if (fld[i][j] == 'E') exit.emplace(i, j);
			fld[i][j] = '.';
		}
		vector<state> updates;
		for (auto i : exit)REP(ax, h)REP(ay, w)
		{
			int qx = i.first, qy = i.second;
			dp[0][qx][qy][ax][ay] = 1;
			updates.push_back(state(0, qx, qy, ax, ay));
		}
		REP(i, h)REP(j, w)
		{
			if (fld[i][j] == '#') continue;
			dp[0][i][j][i][j] = -1;
			updates.push_back(state(0, i, j, i, j));
		}
		REP(i, 2)REP(qx, h)REP(qy, w)REP(ax, h)REP(ay, w) updates.push_back(state(i, qx, qy, ax, ay));
		while (!updates.empty())
		{
			vector<state> nexts;
			for (auto tmp : updates)
			//REP(i, 2)REP(qx, h)REP(qy, w)REP(ax, h)REP(ay, w)
			{
				int i, qx, qy, ax, ay;
				tie(i, qx, qy, ax, ay) = tmp;
				if (!valid(qx, qy, h, w) || !valid(ax, ay, h, w) || dp[i][qx][qy][ax][ay] != 0) continue;
				if (i == 0)
				{
					set<int> st;
					st.insert(dp[1][qx][qy][ax][ay]);
					REP(j, 4)
					{
						int nx = qx + dx[j], ny = qy + dy[j];
						if (!valid(nx, ny, h, w) || fld[nx][ny] == '#') continue;
						st.insert(dp[1][nx][ny][ax][ay]);
					}
					if (st.size() == 1 && *st.begin() == -1)
					{
						dp[i][qx][qy][ax][ay] = -1;
					}
					else if (st.count(1))
					{
						dp[i][qx][qy][ax][ay] = 1;
					}
				}
				else
				{
					set<int> st;
					st.insert(dp[0][qx][qy][ax][ay]);
					REP(j, 4)
					{
						int nx = ax + dx[j], ny = ay + dy[j];
						if (!valid(nx, ny, h, w) || fld[nx][ny] == '#') continue;
						st.insert(dp[0][qx][qy][nx][ny]);
					}
					if (st.size() == 1 && *st.begin() == 1)
					{
						dp[i][qx][qy][ax][ay] = 1;
					}
					else if (st.count(-1))
					{
						dp[i][qx][qy][ax][ay] = -1;
					}
				}
				if (dp[i][qx][qy][ax][ay] != 0)
				{
					if (dp[1 - i][qx][qy][ax][ay] == 0)
					{
						nexts.push_back(state(1 - i, qx, qy, ax, ay));
					}
					REP(i, 2)REP(j, 4)REP(k, 4)
					{
						if (!valid(qx + dx[j], qy + dy[j], h, w) || !valid(ax + dx[k], ay + dy[k], h, w) || dp[i][qx + dx[j]][qy + dy[j]][ax + dx[k]][ay + dy[k]] != 0) continue;
						nexts.push_back(state(i, qx + dx[j], qy + dy[j], ax + dx[k], ay + dy[k]));
					}
				}
			}
			sort(ALL(updates));
			updates.erase(unique(ALL(updates)), updates.end());
			updates = nexts;
		}
		

		int ans = dp[0][queen.first][queen.second][army.first][army.second];
		if (ans == 1) cout << "Queen can escape." << endl;
		else if (ans == 0) cout << "Queen can not escape and Army can not catch Queen." << endl;
		else cout << "Army can catch Queen." << endl;
	}

	return 0;
}
accuracy: 1
time_ms: 7970
memory_kb: 52528
final_rank: 20