Problem:
Karakuri Doll
からくり人形
English text is not available in this practice contest.
からくり人形師の JAG 氏は，長年の研究の果てに，伝統技術と最新技術を融合させたすばらしいお茶汲み人形の開発に成功した．このお茶汲み人形は，下の図のように格子に区切られた家の中で，台所（K）でお茶の入った湯飲みを乗せるとそれを主人（M）の居場所まで持っていき，主人が飲み終わった湯飲みを乗せると台所まで戻っていくという仕事をする．ただし，この人形は台所と主人の間の往復経路を自分で見つけられるほど賢くはない．使用者はこの人形にプログラムをあらかじめ入力して，人形がきちんと往復できるようにする必要がある．
図 F-1: 家の構造の例
人形が受理する命令は「左に曲がる」と「右に曲がる」の 2 つであり，人形に入力可能なプログラムは命令の有限な列である．人形は台所を出発した後，壁（図中「#」で表されたマス）にぶつかるまで前進し，壁にぶつかると最初の命令に従って左または右に方向転換する．以降，再び壁にぶつかるまで前進し，ぶつかったら次の命令を実行し，以下同様に物事が進む．方向転換してもなお壁にぶつかって前進できないときは，その場所から移動しないまま次の命令を実行する．壁にぶつかったとき，実行する命令が残っていなければ人形は停止する．これをプログラムの順実行と呼ぶ．
主人の居場所から台所に戻るときは，プログラムの命令列を逆順に実行し，さらに左右反対に方向転換する．これをプログラムの逆実行と呼ぶ．命令の実行順序および方向転換以外の挙動は順実行と同じである．
たとえば，上の図の家で，この人形に「右，右，左」というプログラムを与えると，往路では地点 a で右，地点 b で右，地点 c で左にそれぞれ方向転換して主人の居場所に到着する．また，復路では地点 c で右，地点 b で左，地点 a で左にそれぞれ方向転換して台所に帰還する．一方，「左，左」というプログラムを与えると，人形はまず地点 a で左に方向転換する．直進しようとするが，そのまま左側の壁にぶつかるため，地点 a にとどまったまま 2 番目の命令にしたがって左に方向転換する．そして直進して台所まで戻ってきたところで壁にぶつかり，命令が残っていないので停止する．
ところで，JAG 氏は大きな過ちを犯していた．実は，どのようなプログラムを与えても主人の居場所までたどり着けない場合が存在するのである．また，主人の居場所に着いたとしても，湯飲みを台所まで持って帰れない場合もある．
あなたの仕事は，ある家の中でこの人形を使ったときに，この人形が主人の居場所に到着できるか，そして台所に帰還できるかを判断するプログラムを書くことである．
Input
入力は複数のデータセットからなり，最後に 0 0 と書かれた行が入力の終わりを示す．データセットの数は 128 個以下である．
各データセットの最初の行には，家の大きさを表す 2 つの整数
W
,
H
がスペース区切りで書かれる．これらの整数は 3 ≦
W
≦ 64, 3 ≦
H
≦ 16 を満たす．続く
H
行は部屋の構造を意味する．各行は
W
文字から構成され，「
#
」は壁を，「
.
」（ピリオド）は床を，「
K
」は台所を，「
M
」は主人の居場所をそれぞれ示す．これら以外の文字は含まれない．
この家の最外部は，常に壁（「
#
」）であることが保証されている．また「
K
」と「
M
」は，各データセットについて常に 1 つずつ存在して，3 方向が壁（「
#
」），残りの 1 方向が床（「
.
」）であると仮定してよい．
Output
各データセットに対して，以下の記述のとおりにメッセージを 1 行に出力しなさい．
どのようなプログラムを与えても主人の居場所に到着しない場合は「He cannot bring tea to his master.」
主人の居場所には到着するが，その後に台所に帰還するようにプログラムできない場合は「He cannot return to the kitchen.」
主人の居場所に到着して，台所に帰還するようにプログラムできる場合は「He can accomplish his mission.」
ここで，主人の居場所に到着するとは，人形を台所に置いて壁のない方向に向けた状態から，プログラムを順実行したときに，停止時点において主人の居場所に人形が存在することを指す．台所に帰還するとは，人形を主人の居場所に置いて壁のない方向に向けた状態から，プログラムを逆実行したときに，停止時点において台所に人形が存在することを指す．停止時点における人形の向きは問わない．また，往路，復路ともに，経路の途中で台所または主人を通過しても構わない．ただし，経路の途中で台所または主人を通過したとしても，停止時点において人形がそれ以外の場所にいるときは，主人の居場所に到着した，あるいは台所に帰還したとはみなされない．
Sample Input
5 3
#####
#K.M#
#####
9 5
#########
#.....###
#.###..M#
#K#######
#########
9 5
#########
#K......#
####.####
####M####
#########
9 5
#########
#M......#
####.####
####K####
#########
7 9
#######
#####M#
#####.#
#.....#
#.###.#
#.....#
#.#####
#K#####
#######
7 6
#######
#####.#
##....#
#K..#.#
###M#.#
#######
7 8
#######
##...##
###.#M#
#.....#
#.#...#
#.#..##
#.K####
#######
9 6
#########
###..##.#
##......#
#K....#.#
##..#M#.#
#########
9 6
#########
#.#######
#....#M.#
#.#...#.#
###K#...#
#########
12 7
############
###...####.#
##K#...M##.#
##.....#...#
#........#.#
###..#...#.#
############
23 16
#######################
#########...###########
##########.###.########
##########.....########
##########.#.#.###...##
########.#.#.######.###
########............###
########.###.######.###
############.######.###
#K...........######.###
####.#######.######.###
#
...(truncated)

Submitted solutions:

code_snippet: #line 2 "cp-library/src/cp-template.hpp"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using uint = unsigned int;
using ull  = unsigned long long;
using i32 = int;
using u32 = unsigned int;
using i64 = long long;
using u64 = unsigned long long;
using i128 = __int128_t;
template < class T > bool chmin(T& a, T b) { if(a > b) { a = b; return true; } return false; }
template < class T > bool chmax(T& a, T b) { if(a < b) { a = b; return true; } return false; }
template < class T, class U > T ceil (T x, U y) { return (x > 0 ? (x + y - 1) / y :           x / y); }
template < class T, class U > T floor(T x, U y) { return (x > 0 ?           x / y : (x - y + 1) / y); }
int popcnt(i32 x) { return __builtin_popcount(x); }
int popcnt(u32 x) { return __builtin_popcount(x); }
int popcnt(i64 x) { return __builtin_popcountll(x); }
int popcnt(u64 x) { return __builtin_popcountll(x); }

#line 2 "cp-library/src/utility/rep_itr.hpp"
template < class T > struct itr_rep {
    T i, d;
    constexpr itr_rep(const T i) noexcept : i(i), d(1) {}
    constexpr itr_rep(const T i, const T d) noexcept : i(i), d(d) {}
    void operator++() noexcept { i += d; }
    constexpr int operator*() const noexcept { return i; }
    constexpr bool operator!=(const itr_rep x) const noexcept { return d > 0 ? i < x.i : i > x.i; }
};

template < class T > struct rep {
    const itr_rep< T > s, t;
    constexpr rep(const T t) noexcept : s(0), t(t) {}
    constexpr rep(const T s, const T t) noexcept : s(s), t(t) {}
    constexpr rep(const T s, const T t, const T d) noexcept : s(s, d), t(t, d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};

template < class T > struct revrep {
    const itr_rep < T > s, t;
    constexpr revrep(const T t) noexcept : s(t - 1, -1), t(-1, -1) {}
    constexpr revrep(const T s, const T t) noexcept : s(t - 1, -1), t(s - 1, -1) {}
    constexpr revrep(const T s, const T t, const T d) noexcept : s(t - 1, -d), t(s - 1, -d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};
#line 3 "cp-library/src/utility/io.hpp"

/* 128bit integer */
istream& operator>>(istream& is, i128& x) {
    std::string s; is >> s;
    int pm = (s[0] == '-');
    x = 0;
    for(int i : rep(pm, int(s.size()))) x = x * 10 + (s[i] - '0');
    if(pm) x *= -1;
    return is;
}
ostream& operator<<(ostream& os, const i128& x) {
    if(x == 0) return os << '0';
    i128 y = x;
    if(y < 0) { os << '-'; y *= -1; }
    std::vector<int> ny;
    while(y > 0) { ny.push_back(y % 10); y /= 10; }
    for(int i : revrep(ny.size())) os << ny[i];
    return os;
}

template < class S, class T > istream& operator>>(istream& is,       std::pair< S, T >& x) { is >> x.first        >> x.second; return is; }
template < class S, class T > ostream& operator<<(ostream& os, const std::pair< S, T >& x) { os << x.first << " " << x.second; return os; }

namespace scanner {
    struct sca {
        template < class T > operator T() {
            T s; std::cin >> s; return s;
        }
    };
    struct vec {
        int n;
        vec(int n) : n(n) {}
        template < class T > operator std::vector< T >() {
            std::vector< T > v(n);
            for(T& x : v) std::cin >> x;
            return v;
        }
    };
    struct mat {
        int h, w;
        mat(int h, int w) : h(h), w(w) {}
        template < class T > operator std::vector< std::vector< T > >() {
            std::vector m(h, std::vector< T >(w));
            for(std::vector< T >& v : m) for(T& x : v) std::cin >> x;
            return m;
        }
    };
    struct speedup {
        speedup() {
            std::cin.tie(0);
            std::ios::sync_with_stdio(0);
        }
    } speedup_instance;
}
scanner::sca in() { return scanner::sca(); }
scanner::vec in(int n) { return scanner::vec(n); }
scanner::mat in(int h, int w) { return scanner::mat(h, w); }

namespace printer {
    void precision(int d) { std::cout << std::fixed << std::setprecision(d); }
    void flush() { std::cout.flush(); }
}

template < class T >
ostream& operator<<(ostream& os, const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) { os << a[i]; if(i != n - 1) os << ' '; }
    return os;
}

int print() { std::cout << '\n'; return 0; }
template < class head, class... tail > int print(head&& h, tail&&... t) {
    std::cout << h; if(sizeof...(tail)) std::cout << ' ';
    return print(std::forward<tail>(t)...);
}
template < class T > int print_n(const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) std::cout << a[i] << "\n";
    return 0;
}


#line 2 "cp-library/src/utility/key_val.hpp"

template < class K, class V >
struct key_val {
    K key; V val;
    key_val() {}
    key_val(K key, V val) : key(key), val(val) {}
    template < std::size_t Index >
    std::tuple_element_t< Index, key_val >& get() {
        if constexpr (Index == 0) return key;
        if constexpr (Index == 1) return val;
    }
};

namespace std {

template < class K, class V > struct tuple_size < key_val< K, V > > : integral_constant< size_t, 2 > {};
template < class K, class V > struct tuple_element < 0, key_val< K, V > > { using type = K; };
template < class K, class V > struct tuple_element < 1, key_val< K, V > > { using type = V; };

}
#line 2 "cp-library/src/utility/vec_op.hpp"
template < class T > key_val< int, T > max_of(const vector< T >& a) {
    int i = std::max_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class T > key_val< int, T > min_of(const vector< T >& a) {
    int i = std::min_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class S, class T > S sum_of(const vector< T >& a) {
    S sum = 0;
    for(const T x : a) sum += x;
    return sum;
}
template < class S, class T > vector< S > freq_of(const vector< T >& a, T L, T R) {
    vector< S > res(R - L, S(0));
    for(const T x : a) res[x - L] += 1;
    return res;
}
template < class S, class T > struct prefix_sum {
    vector< S > s;
    prefix_sum(const vector< T >& a) : s(a) {
        s.insert(s.begin(), S(0));
        for(int i : rep(a.size())) s[i + 1] += s[i];
    }
    // [L, R)
    S sum(int L, int R) { return s[R] - s[L]; }
};
#line 3 "cp-library/src/utility/heap.hpp"

template < class T > using heap_min = std::priority_queue< T, std::vector< T >, std::greater< T > >;
template < class T > using heap_max = std::priority_queue< T, std::vector< T >, std::less< T > >;

#line 27 "cp-library/src/cp-template.hpp"

#line 1 "cp-library/src/algorithm/bin_search.hpp"
template < class T, class F >
T bin_search(T ok, T ng, F f) {
    while(abs(ng - ok) > 1) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}

template < class T, class F >
T bin_search_real(T ok, T ng, F f, int step = 80) {
    while(step--) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}
#line 2 "cp-library/src/algorithm/argsort.hpp"

template < class T > std::vector< int > argsort(const std::vector< T > &a) {
    std::vector< int > ids((int)a.size());
    std::iota(ids.begin(), ids.end(), 0);
    std::sort(ids.begin(), ids.end(), [&](int i, int j) {
        return a[i] < a[j] || (a[i] == a[j] && i < j);
    });
    return ids;
}
#line 1 "macro.hpp"
namespace macro {

using size_type = int;
template < class container > void  sort(container& a) { std::sort(std:: begin(a), std:: end(a)); }
template < class container > void rsort(container& a) { std::sort(std::rbegin(a), std::rend(a)); }
template < class container > void reverse(container& a) { std::reverse(std::begin(a), std::end(a)); }
template < class container > void unique(container& a) {
    std::sort(std::begin(a), std::end(a));
    a.erase(std::unique(std::begin(a), std::end(a)), std::end(a));
}
template < class container > container  sorted(const container& a) { container b = a;  sort(b); return std::move(b); }
template < class container > container rsorted(const container& a) { container b = a; rsort(b); return std::move(b); }
template < class container, class compare > void sort(container& a, const compare& cmp) { std::sort(std::begin(a), std::end(a), cmp); }
template < class container, class compare > container sorted(const container& a, const compare& cmp) { container b = a; sort(b, cmp); return std::move(b); }
template < class container, class value > size_type lower_bound(const container& a, const value& x) { return std::lower_bound(std::begin(a), std::end(a), x) - std::begin(a); }
template < class container, class value > size_type upper_bound(const container& a, const value& x) { return std::upper_bound(std::begin(a), std::end(a), x) - std::begin(a); }

const std::vector<std::pair<size_type, size_type>> dir4 = { {+1,  0}, {-1,  0}, { 0, +1}, { 0, -1} };
const std::vector<std::pair<size_type, size_type>> dir8 = { {-1, -1}, {-1,  0}, {-1, +1}, { 0, -1}, { 0, +1}, {+1, -1}, {+1,  0}, {+1, +1} };

#ifdef _DEBUG
#define debug(x) std::cout << "[" << __LINE__ << "] " << #x << ": " << x << std::endl
#else
#define debug(x)
#endif

template < class container > void concat(container& a, const container& b) {
    a.insert(std::end(a), std::begin(b), std::end(b));
}
std::vector<size_type> iota(const size_type n) {
    std::vector<size_type> I(n);
    std::iota(std::begin(I), std::end(I), 0);
    return I;
}
template < class container > std::vector<size_type> sort_idx(const container& a) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return a[i] < a[j] or (a[i] == a[j] and i < j); });
    return I;
}
template < class container, class compare > std::vector<size_type> sort_idx(const container& a, const compare& cmp) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return cmp(a[i], a[j]) or (a[i] == a[j] and i < j); });
    return std::move(I);
}

struct grid {
    using size_type = int;
    size_type H, W;
    grid(const size_type H, const size_type W) : H(H), W(W) {}
    bool contains(const size_type i, const size_type j) {
        return 0 <= i and i < H and 0 <= j and j < W;
    }
};

using f64 = long double;

template < class T > vector< T >& operator++(vector< T >& a) { for(T& x : a) x++; return a; }
template < class T > vector< T >& operator--(vector< T >& a) { for(T& x : a) x--; return a; }
template < class T > vector< T >  operator++(vector< T >& a, signed) { vector< T > res = a; for(T& x : a) x++; return res; }
template < class T > vector< T >  operator--(vector< T >& a, signed) { vector< T > res = a; for(T& x : a) x--; return res; }

} // namespace macro

using namespace macro;
#line 3 "A.cpp"

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

string solve(const int w, const int h) {
    vector<string> a = in(h);
    int sx, sy, sd, tx, ty, td;
    for(int x : rep(h)) for(int y : rep(w)) {
        if(a[x][y] == 'K') tie(sx, sy) = make_pair(x, y), a[x][y] = '.';
        if(a[x][y] == 'M') tie(tx, ty) = make_pair(x, y), a[x][y] = '.';
    }
    for(int d : rep(4)) {
        if(a[sx + dx[d]][sy + dy[d]] == '.') sd = d;
        if(a[tx + dx[d]][ty + dy[d]] == '.') td = d;
    }

    const int n = h * w * 4;
    auto f = [&](int x, int y, int d) { return (x * w + y) * 4 + d; };
    auto f_inv = [&](int v) { return make_tuple((v / 4) / w, (v / 4) % w, v % 4); };

    vector<int> nxt(n, -1);
    for(int x : rep(h)) for(int y : rep(w)) for(int d : rep(4)) {
        if(a[x][y] == '.') {
            int nx = x, ny = y;
            while(a[nx + dx[d]][ny + dy[d]] == '.') nx += dx[d], ny += dy[d];
            nxt[f(x, y, d)] = f(nx, ny, d);
        }
    }
    bool one_way = [&] {
        vector vis(n, 0);
        queue<int> que;
        que.push(nxt[f(sx, sy, sd)]);
        while(not que.empty()) {
            int v = que.front(); que.pop();
            if(vis[v]) continue;
            vis[v] = true;
            auto [x, y, d] = f_inv(v);
            if(make_pair(x, y) == make_pair(tx, ty)) return true;
            int nv = nxt[f(x, y, (d + 1) % 4)];
            if(not vis[nv]) que.push(nv);
                nv = nxt[f(x, y, (d + 3) % 4)];
            if(not vis[nv]) que.push(nv);
        }
        return false;
    }();
    if(not one_way) return "He cannot bring tea to his master."s;

    vector prev(2, vector(n, vector<int>()));
    for(int x : rep(h)) for(int y : rep(w)) for(int d : rep(4)) {
        if(a[x][y] == '.' and a[x + dx[d]][y + dy[d]] == '#') {
            prev[0][nxt[f(x, y, (d + 1) % 4)]].push_back(f(x, y, d));
            prev[1][nxt[f(x, y, (d + 3) % 4)]].push_back(f(x, y, d));
        }
    }
    bool two_way = [&] {
        vector vis(n, vector(n, 0));
        queue<pair<int,int>> que;
        for(int d : rep(4)) {
            if(a[sx + dx[d]][sy + dy[d]] == '#') {
                que.push({nxt[f(sx, sy, sd)], f(sx, sy, d)});
            }
        }
        while(not que.empty()) {
            auto [u, v] = que.front(); que.pop();
            if(vis[u][v]) continue;
            vis[u][v] = true;
            auto [ux, uy, ud] = f_inv(u);
            auto [vx, vy, vd] = f_inv(v);
            if(make_pair(ux, uy) == make_pair(tx, ty) and v == nxt[f(tx, ty, td)]) return true;
            int nu = nxt[f(ux, uy, (ud + 1) % 4)];
            for(int nv : prev[1][v]) if(not vis[nu][nv]) que.push({nu, nv});
                nu = nxt[f(ux, uy, (ud + 3) % 4)];
            for(int nv : prev[0][v]) if(not vis[nu][nv]) que.push({nu, nv});
        }
        return false;
    }();
    if(not two_way) return "He cannot return to the kitchen."s;
    return "He can accomplish his mission."s;
}

int main() {
    while(true) {
        int w = in(), h = in();
        if(make_pair(w, h) == make_pair(0, 0)) return 0;
        print(solve(w, h));
    }
}
accuracy: 1
time_ms: 530
memory_kb: 69144
final_rank: 16

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 main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout << fixed << setprecision(15);

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

    while (true) {
        int W, H;
        cin >> W >> H;
        if (W == 0 && H == 0) break;

        vector<string> grid(H);
        for (auto& x : grid) cin >> x;

        int M = 4 * W * H;

        auto encode = [&](int i, int j, int d) { return 4 * (W * i + j) + d; };
        auto decode = [&](int x) {
            return make_tuple(x / 4 / W, x / 4 % W, x % 4);
        };

        auto check = [&](int i, int j, int d) {
            int ni = i + di[d], nj = j + dj[d];
            return (0 <= ni && ni < H && 0 <= nj && nj < W &&
                    grid[ni][nj] != '#');
        };

        vector<int> to(M);
        rep(i, 0, H) rep(j, 0, W) {
            if (grid[i][j] == '#') continue;
            rep(d, 0, 4) {
                int ni = i, nj = j;
                while (check(ni, nj, d)) {
                    ni += di[d];
                    nj += dj[d];
                }
                to[encode(i, j, d)] = encode(ni, nj, d);
            }
        }
        vector<vector<int>> nxt(2, vector<int>(M));
        vector<vector<vector<int>>> G_rev(2, vector<vector<int>>(M));
        rep(i, 0, H) rep(j, 0, W) {
            if (grid[i][j] == '#') continue;
            rep(d, 0, 4) {
                if (check(i, j, d)) continue;
                rep(k, 0, 2) {
                    int nd = (d + (2 * k - 1) + 4) % 4;
                    nxt[k][encode(i, j, d)] = to[encode(i, j, nd)];
                    G_rev[k][to[encode(i, j, nd)]].push_back(encode(i, j, d));
                }
            }
        }

        stack<pair<int, int>> st;
        set<pair<int, int>> visited;

        stack<int> st1;
        set<int> visited1;

        int gi, gj;

        rep(i, 0, H) rep(j, 0, W) {
            if (grid[i][j] == 'K') {
                rep(d1, 0, 4) rep(d2, 0, 4) {
                    if (check(i, j, d1)) {
                        int x1 = encode(i, j, d1);
                        int x2 = encode(i, j, d2);

                        st.push({to[x1], x2});
                        visited.insert({to[x1], x2});

                        st1.push(to[x1]);
                        visited1.insert(to[x1]);
                    }
                }
            }
            if (grid[i][j] == 'M') {
                gi = i;
                gj = j;
            }
        }

        bool ok2 = false;

        while (!st.empty()) {
            auto [x1, x2] = st.top();
            st.pop();
            auto [i1, j1, d1] = decode(x1);
            auto [i2, j2, d2] = decode(x2);
            bool b1 = i1 == gi && j1 == gj;
            bool b2 = false;
            rep(d, 0, 4) {
                if (check(gi, gj, d) && to[encode(gi, gj, d)] == x2) {
                    b2 = true;
                }
            }
            if (b1 && b2) {
                ok2 = true;
                break;
            }
            rep(k, 0, 2) {
                int z1 = nxt[k][x1];
                for (auto z2 : G_rev[k ^ 1][x2]) {
                    if (!visited.count({z1, z2})) {
                        st.push({z1, z2});
                        visited.insert({z1, z2});
                    }
                }
            }
        }
        if (ok2) {
            cout << "He can accomplish his mission.\n";
            continue;
        }

        bool ok1 = false;

        while (!st1.empty()) {
            int x = st1.top();
            st1.pop();
            auto [i, j, d] = decode(x);
            if (i == gi && j == gj) {
                ok1 = true;
                break;
            }
            rep(k, 0, 2) {
                int z = nxt[k][x];
                if (!visited1.count(z)) {
                    st1.push(z);
                    visited1.insert(z);
                }
            }
        }

        if (ok1)
            cout << "He cannot return to the kitchen.";
        else
            cout << "He cannot bring tea to his master.";
        // cout << endl;
        cout << "\n";
    }
}
accuracy: 1
time_ms: 210
memory_kb: 8068
final_rank: 1

code_snippet: #include <bits/stdc++.h>
#define ll long long
#define rep(i, n) for(ll i = 0; i < (n); i++)
#define rep2(i, a, b) for(ll i = (a); i < (b); i++)
#define vi vector<int>
#define si(c) int(c.size())

using namespace std;

vi dx = {1, 0, -1, 0}, dy = {0, 1, 0, -1};

int main() {
    while(true) {
        int w, h;
        cin >> w >> h;
        if(!h) exit(0);

        vector a(h, vi(w, 1));
        int sx[2], sy[2], dir[2];
        rep(i, h) rep(j, w) {
            char c;
            cin >> c;
            if(c == 'K') sx[0] = i, sy[0] = j;
            if(c == 'M') sx[1] = i, sy[1] = j;
            if(c == '#') a[i][j] = 0;
        }
        rep(i, 2) rep(j, 4) if(a[sx[i] + dx[j]][sy[i] + dy[j]]) dir[i] = j;

        auto id = [&](int i, int j, int dir) { return (i * w + j) * 4 + dir; };
        int N = h * w * 4, SX = id(sx[0], sy[0], dir[0]), SY = id(sx[1], sy[1], dir[1]);
        vector vis(N, vi(N));
        vector to(N, 0);
        vector cand(2, vector(N, vi()));
        queue<pair<int, int>> q;
        bool tomas = false, flag = false;

        rep(i, h) rep(j, w) rep(d, 4) {
            if(!a[i][j]) continue;
            int ni = i, nj = j;
            while(a[i + dx[d]][j + dy[d]]) i += dx[d], j += dy[d];
            to[id(ni, nj, d)] = id(i, j, d);
            i = ni, j = nj;
        }

        auto nd = [](int d, int t) { return (d + 1 + t * 2) % 4; };

        rep(i, h) rep(j, w) rep(d, 4) {
            if(!a[i][j]) continue;
            if(a[i + dx[d]][j + dy[d]]) continue;
            rep(t, 2) { cand[t][to[id(i, j, nd(d, t))]].emplace_back(id(i, j, d)); }
        }

        rep(d, 4) {
            if(a[sx[0] + dx[d]][sy[0] + dy[d]]) continue;
            vis[to[SX]][id(sx[0], sy[0], d)] = true;
            q.emplace(to[SX], id(sx[0], sy[0], d));
        }

        while(!empty(q)) {
            auto [x, y] = q.front();
            if(x / 4 == SY / 4 and y == to[SY]) {
                flag = true;
                break;
            }
            q.pop();
            rep(t, 2) {
                int nx = to[x / 4 * 4 + nd(x % 4, t)];
                for(auto ny : cand[t ^ 1][y]) {
                    if(!vis[nx][ny]) vis[nx][ny] = true, q.emplace(nx, ny);
                }
            }
        }
        if(!flag) {
            queue<int> q;
            q.emplace(to[SX]);
            vi vis(N);
            vis[to[SX]] = true;
            while(!empty(q)) {
                auto x = q.front();
                if(x / 4 == SY / 4) tomas = true;
                q.pop();
                rep(t, 2) {
                    int nx = to[x / 4 * 4 + nd(x % 4, t)];
                    if(!vis[nx]) vis[nx] = true, q.emplace(nx);
                }
            }
        }

        if(flag) {
            cout << "He can accomplish his mission.";
        } else if(tomas) {
            cout << "He cannot return to the kitchen.";
        } else {
            cout << "He cannot bring tea to his master.";
        }
        cout << endl;
    }
}
accuracy: 1
time_ms: 180
memory_kb: 69156
final_rank: 14

code_snippet: #include <bits/stdc++.h>
#define ll long long
#define rep(i, n) for(ll i = 0; i < (n); i++)
#define rep2(i, a, b) for(ll i = (a); i < (b); i++)
#define vi vector<int>
#define si(c) int(c.size())

using namespace std;

vi dx = {1, 0, -1, 0}, dy = {0, 1, 0, -1};

int main() {
    while(true) {
        int w, h;
        cin >> w >> h;
        if(!h) exit(0);

        vector a(h, vi(w, 1));
        int sx[2], sy[2];
        rep(i, h) rep(j, w) {
            char c;
            cin >> c;
            if(c == 'K') sx[0] = i, sy[0] = j;
            if(c == 'M') sx[1] = i, sy[1] = j;
            if(c == '#') a[i][j] = 0;
        }
        int dir[2] = {};
        rep(i, 2) rep(j, 4) if(a[sx[i] + dx[j]][sy[i] + dy[j]]) dir[i] = j;

        auto id = [&](int i, int j, int dir) { return (i * w + j) * 4 + dir; };
        int N = h * w * 4;
        vector vis(N, vi(N));

        bool tomas = false;
        bool flag = false;

        vector to(N, 0);
        rep(i, h) rep(j, w) rep(d, 4) {
            if(!a[i][j]) continue;
            int ni = i, nj = j;
            while(a[i + dx[d]][j + dy[d]]) i += dx[d], j += dy[d];
            to[id(ni, nj, d)] = id(i, j, d);
            i = ni, j = nj;
        }
        int SX = id(sx[0], sy[0], dir[0]), SY = id(sx[1], sy[1], dir[1]);

        vector cand(2, vector(N, vi()));

        auto nd = [](int d, int t) { return (d + 1 + t * 2) % 4; };

        rep(i, h) rep(j, w) rep(d, 4) {
            if(!a[i][j]) continue;
            if(a[i + dx[d]][j + dy[d]]) continue;
            rep(t, 2) { cand[t][to[id(i, j, nd(d, t))]].emplace_back(id(i, j, d)); }
        }

        queue<pair<int, int>> q;
        rep(d, 4) {
            if(a[sx[0] + dx[d]][sy[0] + dy[d]]) continue;
            vis[to[SX]][id(sx[0], sy[0], d)] = true;
            q.emplace(to[SX], id(sx[0], sy[0], d));
        }

        while(!empty(q)) {
            auto [x, y] = q.front();
            if(x / 4 == SY / 4 and y == to[SY]) {
                flag = true;
                break;
            }
            q.pop();
            rep(t, 2) {
                int nx = to[x / 4 * 4 + nd(x % 4, t)];
                for(auto ny : cand[t ^ 1][y]) {
                    if(!vis[nx][ny]) vis[nx][ny] = true, q.emplace(nx, ny);
                }
            }
        }
        if(!flag) {
            queue<int> q;
            q.emplace(to[SX]);
            vi vis(N);
            vis[to[SX]] = true;
            while(!empty(q)) {
                auto x = q.front();
                if(x / 4 == SY / 4) tomas = true;
                q.pop();
                rep(t, 2) {
                    int nx = to[x / 4 * 4 + nd(x % 4, t)];
                    if(!vis[nx]) vis[nx] = true, q.emplace(nx);
                }
            }
        }

        if(flag) {
            cout << "He can accomplish his mission.";
        } else if(tomas) {
            cout << "He cannot return to the kitchen.";
        } else {
            cout << "He cannot bring tea to his master.";
        }
        cout << endl;
    }
}
accuracy: 1
time_ms: 180
memory_kb: 69192
final_rank: 15

code_snippet: #include <bits/stdc++.h>
#define ll long long
#define rep(i, n) for(ll i = 0; i < (n); i++)
#define rep2(i, a, b) for(ll i = (a); i < (b); i++)
#define vi vector<int>
#define si(c) int(c.size())

using namespace std;

int main() {
    while(true) {
        int w, h;
        cin >> w >> h;
        if(!h) exit(0);

        vector a(h, vi(w, 1));
        int sx[2], sy[2];
        rep(i, h) rep(j, w) {
            char c;
            cin >> c;
            if(c == 'K') sx[0] = i, sy[0] = j;
            if(c == 'M') sx[1] = i, sy[1] = j;
            if(c == '#') a[i][j] = 0;
        }
        int dir[2] = {};
        vector<pair<int, int>> dx{{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
        rep(i, 2) {
            rep(j, 4) {
                auto [x, y] = dx[j];
                int nx = sx[i] + x, ny = sy[i] + y;
                if(a[nx][ny]) dir[i] = j;
            }
        }

        auto id = [&](int i, int j, int dir) { return (i * w + j) * 4 + dir; };
        int N = h * w * 4;
        vector vis(N, vi(N));

        bool tomas = false;
        bool flag = false;

        vector to(N, 0);
        rep(i, h) rep(j, w) rep(d, 4) {
            if(!a[i][j]) continue;
            int ni = i, nj = j;
            while(a[i + dx[d].first][j + dx[d].second]) i += dx[d].first, j += dx[d].second;
            to[id(ni, nj, d)] = id(i, j, d);
            assert(a[ni][nj]);
            i = ni, j = nj;
        }
        int SX = id(sx[0], sy[0], dir[0]), SY = id(sx[1], sy[1], dir[1]);

        vector<vi> rcand(N), lcand(N);
        rep(i, h) rep(j, w) rep(d, 4) {
            if(!a[i][j]) continue;
            if(a[i + dx[d].first][j + dx[d].second]) continue;
            int nd = (d + 1) % 4;
            rcand[to[id(i, j, nd)]].emplace_back(id(i, j, d));
            nd = (d + 3) % 4;
            lcand[to[id(i, j, nd)]].emplace_back(id(i, j, d));
        }

        queue<pair<int, int>> q;
        rep(d, 4) {
            if(a[sx[0] + dx[d].first][sy[0] + dx[d].second]) continue;
            vis[to[SX]][id(sx[0], sy[0], d)] = true;
            q.emplace(to[SX], id(sx[0], sy[0], d));
        }

        auto f = [&](int i) { cout << i / 4 / w << " " << i / 4 % w << " " << i % 4 << " "; };

        while(!empty(q)) {
            auto [x, y] = q.front();
            // f(x), f(y), cout << endl;
            if(x / 4 == SY / 4 and y == to[SY]) {
                flag = true;
                break;
            }
            q.pop();
            {
                int nx = x / 4 * 4 + (x % 4 + 1) % 4;
                nx = to[nx];
                for(auto ny : lcand[y]) {
                    if(!vis[nx][ny]) vis[nx][ny] = true, q.emplace(nx, ny);
                }
            }
            {
                int nx = x / 4 * 4 + (x % 4 + 3) % 4;
                nx = to[nx];
                for(auto ny : rcand[y]) {
                    if(!vis[nx][ny]) vis[nx][ny] = true, q.emplace(nx, ny);
                }
            }
        }
        if(!flag) {
            queue<int> q;
            q.emplace(to[SX]);
            vi vis(N);
            vis[to[SX]] = true;
            while(!empty(q)) {
                auto x = q.front();
                if(x / 4 == SY / 4) tomas = true;
                q.pop();
                for(auto d : {1, 3}) {
                    int nx = x / 4 * 4 + (x % 4 + d) % 4;
                    nx = to[nx];
                    if(!vis[nx]) vis[nx] = true, q.emplace(nx);
                }
            }
        }

        if(flag) {
            cout << "He can accomplish his mission.";
        } else if(tomas) {
            cout << "He cannot return to the kitchen.";
        } else {
            cout << "He cannot bring tea to his master.";
        }
        cout << endl;
    }
}
accuracy: 1
time_ms: 160
memory_kb: 69212
final_rank: 13

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=300005;
const ll INF=1LL<<62;

bool dp[16][64][4][16][64][4][2];
bool can[16][64][4][2];
pair<int,int> to[16][64][4];

vector<int> dh={0,1,0,-1},dw={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];
        int sh=-1,sw=-1,sd=-1,gh=-1,gw=-1,gd=-1;
        for(int i=0;i<H;i++){
            for(int j=0;j<W;j++){
                if(S[i][j]=='K'){
                    sh=i;
                    sw=j;
                    for(int k=0;k<4;k++){
                        if(S[i+dh[k]][j+dw[k]]!='#'){
                            //cout<<i+dh[k]<<" "<<j+dw[k]<<" "<<S[i+dh[k]][j+dw[k]]<<" "<<k<<endl;
                            sd=k;
                        }
                    }
                }
                if(S[i][j]=='M'){
                    gh=i;
                    gw=j;
                    for(int k=0;k<4;k++){
                        if(S[i+dh[k]][j+dw[k]]!='#') gd=k;
                    }
                }
            }
        }
        for(int a=0;a<H;a++) for(int b=0;b<W;b++) for(int c=0;c<4;c++) for(int d=0;d<H;d++) for(int e=0;e<W;e++) for(int f=0;f<4;f++) for(int g=0;g<2;g++) dp[a][b][c][d][e][f][g]=false;
        
        //cout<<sh<<" "<<sw<<" "<<sd<<" "<<gh<<" "<<gw<<" "<<gd<<endl;
        
        for(int i=0;i<H;i++){
            for(int j=0;j<W;j++){
                if(S[i][j]=='#') continue;
                for(int k=0;k<4;k++){
                    int toh1=i,tow1=j;
                    while(S[toh1+dh[k]][tow1+dw[k]]!='#'){
                        toh1+=dh[k];
                        tow1+=dw[k];
                    }
                    to[i][j][k]=mp(toh1,tow1);
                }
            }
        }
        
        queue<tuple<int,int,int,int,int,int,int>> Q;
        for(int k=0;k<4;k++){
            if(k!=sd){
                dp[sh][sw][sd][sh][sw][k][0]=true;
                Q.push({sh,sw,sd,sh,sw,k,0});
            }
        }
        while(!Q.empty()){
            auto [h1,w1,d1,h2,w2,d2,f]=Q.front();Q.pop();
            if(f==0){
                assert(S[h2+dh[d2]][w2+dw[d2]]=='#');
                auto [toh1,tow1]=to[h1][w1][d1];
                int toh2=h2,tow2=w2;
                while(1){
                    if(!dp[toh1][tow1][d1][toh2][tow2][d2][1]){
                        dp[toh1][tow1][d1][toh2][tow2][d2][1]=true;
                        Q.push({toh1,tow1,d1,toh2,tow2,d2,1});
                    }
                    toh2-=dh[d2];
                    tow2-=dw[d2];
                    
                    if(S[toh2][tow2]=='#') break;
                }
            }else{
                assert(S[h1+dh[d1]][w1+dw[d1]]=='#');
                for(int k=1;k<4;k+=2){
                    int tod1=(d1+k)%4,tod2=(d2+k)%4;
                    if(S[h2+dh[tod2]][w2+dw[tod2]]!='#') continue;
                    if(!dp[h1][w1][tod1][h2][w2][tod2][0]){
                        dp[h1][w1][tod1][h2][w2][tod2][0]=true;
                        Q.push({h1,w1,tod1,h2,w2,tod2,0});
                    }
                }
            }
        }
        
        bool f=false;
        
        for(int k=0;k<4;k++){
            if(gd==k) continue;
            f|=dp[gh][gw][k][gh][gw][gd][1];
        }
        
        if(f){
            cout<<"He can accomplish his mission.\n";
            continue;
        }
        
        for(int a=0;a<H;a++) for(int b=0;b<W;b++) for(int c=0;c<4;c++) for(int g=0;g<2;g++) can[a][b][c][g]=false;
        
        queue<tuple<int,int,int,int>> QQ;
        QQ.push({sh,sw,sd,0});
        while(!QQ.empty()){
            auto [h,w,d,f]=QQ.front();QQ.pop();
            if(f==0){
                auto [toh,tow]=to[h][w][d];
                if(!can[toh][tow][d][1]){
                    can[toh][tow][d][1]=true;
                    QQ.push({toh,tow,d,1});
                }
            }else{
                for(int k=1;k<4;k+=2){
                    int tod=(d+k)%4;
                    if(!can[h][w][tod][0]){
                        can[h][w][tod][0]=true;
                        QQ.push({h,w,tod,0});
                    }
                }
            }
        }
        
        if(can[gh][gw][gd^2][1]) cout<<"He cannot return to the kitchen.\n";
        else cout<<"He cannot bring tea to his master.\n";
    }
}
accuracy: 1
time_ms: 510
memory_kb: 36612
final_rank: 10

code_snippet: #include <cassert>
#include <iostream>
#include <string>
#include <map>
#include <set>
#include <tuple>
#include <vector>
#include <queue>
using namespace std;

const int MAX_H = 20;
const int MAX_W = 70;
const int dx[] = {-1, 0, 1, 0};
const int dy[] = {0, 1, 0, -1};
const int UP = 0;
const int RIGHT = 1;
const int DOWN = 2;
const int LEFT = 3;
const int DIRECT[] = {UP, RIGHT, DOWN, LEFT};
// x0, y0, d0, x1, y1, d1
using Pos = tuple<int, int, int, int, int, int>;

int h, w;
string field[MAX_H];
map<Pos, Pos> used;

string solve() {
    for(int i = 0; i < h; i++) {
        cin >> field[i];
    }
    used.clear();
    int mx = -1, my = -1, md = -1;
    int kx = -1, ky = -1, kd = -1;
    for(int i = 0; i < h; i++) {
        for(int j = 0; j < w; j++) {
            if(field[i][j] == 'K' || field[i][j] == 'M') {
                int d = -1;
                for(int k = 0; k < 4; k++) {
                    int nx = i + dx[k], ny = j + dy[k];
                    if(field[nx][ny] != '#') {
                        d = k;
                        break;
                    }
                }
                assert(d != -1);
                if(field[i][j] == 'K') {
                    kx = i;
                    ky = j;
                    kd = d;
                } else {
                    mx = i;
                    my = j;
                    md = d;
                }
            }
        }
    }
    assert(mx != -1);
    assert(my != -1);
    queue<Pos> q;
    for(int i = 0; i < 4; i++) {
        q.push(make_tuple(mx, my, md, mx, my, i));
          used[make_tuple(mx, my, md, mx, my, i)] = 
            make_tuple(-1, -1, -1, -1, -1, -1);
    }
    bool can_return = false, can_reach = false;
    while(!q.empty()) {
        auto now = q.front(); q.pop();
        int x0 = get<0>(now), y0 = get<1>(now), d0 = get<2>(now),
            x1 = get<3>(now), y1 = get<4>(now), d1 = get<5>(now);
        // cerr << x0 << " " << y0 << " " << d0 << " "
        //      << x1 << " " << y1 << " " << d1 << endl;
        assert(field[x0][y0] != '#');
        assert(field[x1][y1] != '#');
        while(field[x0 + dx[d0]][y0 + dy[d0]] != '#') {
            x0 += dx[d0]; y0 += dy[d0];
        }
        if(x1 == kx && y1 == ky) {
            can_reach = true;
        }
        while(field[x1][y1] != '#') {
            for(int k = 1; k < 4; k += 2) {
                int nd0 = (d0 + k) % 4, nd1 = (d1 + k) % 4;
                if(x0 == kx && y0 == ky && x1 == kx && y1 == ky && d1 == (kd + 2) % 4) {
                    can_return = true;
                    // auto f = now;
                    // while(get<0>(f) != -1) {
                    //     cout << get<0>(f) << " " << get<1>(f) << " " << get<2>(f) << " "
                    //          << get<3>(f) << " " << get<4>(f) << " " << get<5>(f) << endl;
                    //     f = used[f];
                    // }
                    break;
                }
                // cerr << x1 - dx[nd1] << " " << y1 - dy[nd1] << endl;
                if(field[x1 - dx[nd1]][y1 - dy[nd1]] == '#') {
                    Pos nxt = make_tuple(x0, y0, nd0, x1, y1, nd1);
                    if(!used.count(nxt)) {
                        used[nxt] = now;
                        q.push(nxt);
                    }
                }
            }
            x1 += dx[d1];
            y1 += dy[d1];
        }
    }
    if(can_return) return "He can accomplish his mission.";
    else if(can_reach) return "He cannot return to the kitchen.";
    else return "He cannot bring tea to his master.";
}

int main() {
    vector<string> ans;
    while(1) {
        cin >> w >> h;
        if(w == 0 && h == 0) break;
        ans.push_back(solve());
    }
    for(auto &i : ans) cout << i << endl;
}
accuracy: 1
time_ms: 2680
memory_kb: 29764
final_rank: 17

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

using namespace std;

#define eps 1e-9
#define INF 2000000000              // 2e9
#define LLINF 2000000000000000000ll // 2e18 (llmax:9e18)
#define all(x) (x).begin(), (x).end()
#define sq(x) ((x) * (x))

#define rep(i, x) for (int i = 0; i < (int)(x); i++)
#define drep(i, x) for (int i = ((int)(x)-1); i >= 0; i--)

#define popcount __builtin_popcount
#define next __next
#define prev __prev

#ifndef LOCAL
#define dmp(...) ;
#else
#define dmp(...)                                                               \
  cerr << "[ " << #__VA_ARGS__ << " ] : " << dump_str(__VA_ARGS__) << endl
#endif

// ---------------- Utility ------------------

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

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

template <class T>
using MaxHeap = priority_queue<T>;

template <class T>
using MinHeap = priority_queue<T, vector<T>, greater<T>>;

template <class T>
vector<T> vect(int len, T elem) {
  return vector<T>(len, elem);
}

// ----------------- Input -------------------

template <class T, class U>
istream &operator>>(istream &is, pair<T, U> &p) {
  return is >> p.first >> p.second;
}

template <class T>
istream &operator>>(istream &is, vector<T> &vec) {
  for (int i = 0; i < vec.size(); i++) is >> vec[i];
  return is;
}

// ----------------- Output ------------------

template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
  return os << p.first << ',' << p.second;
}

template <class T>
ostream &operator<<(ostream &os, const vector<T> &v) {
  for (const T &e : v) os << e << " ";
  return os;
}

template <class T>
ostream &operator<<(ostream &os, const deque<T> &d) {
  for (const T &e : d) os << e << " ";
  return os;
}

template <class T>
ostream &operator<<(ostream &os, const set<T> &s) {
  os << "{ ";
  for (const T &e : s) os << e << " ";
  return os << "}";
}

template <class T, class U>
ostream &operator<<(ostream &os, const map<T, U> &m) {
  os << "{ ";
  for (const auto &[key, val] : m) os << "( " << key << " -> " << val << " ) ";
  return os << "}";
}

template <class TupleTy, size_t... I>
void dump_tuple(ostream &os, const TupleTy t, std::index_sequence<I...>) {
  (..., (os << (I == 0 ? "" : ",") << std::get<I>(t)));
}

template <class... Args>
ostream &operator<<(ostream &os, const tuple<Args...> &t) {
  os << "(";
  dump_tuple(os, t, std::make_index_sequence<sizeof...(Args)>());
  return os << ")";
}

void dump_str_rec(ostringstream &) {}

template <class Head, class... Tail>
void dump_str_rec(ostringstream &oss, Head &&head, Tail &&... tail) {
  oss << ", " << head;
  dump_str_rec(oss, forward<Tail>(tail)...);
}

template <class T, class... U>
string dump_str(T &&arg, U &&... args) {
  ostringstream oss;
  oss << arg;
  dump_str_rec(oss, forward<U>(args)...);
  return oss.str();
}

// --------------- Fast I/O ------------------

void fastio() {
  cin.tie(0);
  ios::sync_with_stdio(0);
  cout << fixed << setprecision(20);
}

// ------------------ ACL --------------------

// #include <atcoder/modint>
// constexpr int MOD = 998244353;
// constexpr int MOD = 1000000007;
// using mint = atcoder::static_modint<MOD>;
// ostream &operator<<(ostream &os, const mint &v) {
//   return os << v.val();
// }

// ------------ End of template --------------

#define endl "\n"
using ll = long long;
using pii = pair<int, int>;

const bool multitest = false;

struct Graph {
  int V;
  vector<vector<int>> G;
  Graph() {}
  Graph(int V) : V(V) { G.resize(V); }
  void add_edge(int a, int b) { G[a].push_back(b); }
  size_t size() const { return G.size(); }
  const vector<int> &operator[](int id) const { return G[id]; }
};

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

bool solve() {
  int h, w;
  cin >> w >> h;

  if (h == 0 && w == 0) return false;

  vector<string> f(h);
  cin >> f;

  auto out_of_borders = [&](int x, int y) {
    return (x < 0 || x >= h || y < 0 || y >= w);
  };

  auto go = vect(h, vect(w, vect(4, pii(-1, -1))));
  auto rev = vect(h, vect(w, vect(4, vector<pii>())));
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      if (f[i][j] == '#') continue;
      for (int d = 0; d < 4; d++) {
        int x = i, y = j;
        while (!out_of_borders(x + dx[d], y + dy[d]) &&
               f[x + dx[d]][y + dy[d]] != '#') {
          x += dx[d];
          y += dy[d];
        }
        go[i][j][d] = pii(x, y);
        rev[x][y][d].emplace_back(i, j);
      }
    }
  }

  auto encode = [&](int ax, int ay, int ad, int bx, int by, int bd) {
    return (4 * w * ax + 4 * ay + ad) * 4 * w * h + (4 * w * bx + 4 * by + bd);
  };

  auto decode = [&](int id, int &ax, int &ay, int &ad, int &bx, int &by,
                    int &bd) {
    bd = id % 4, id /= 4;
    by = id % w, id /= w;
    bx = id % h, id /= h;
    ad = id % 4, id /= 4;
    ay = id % w, id /= w;
    ax = id % h, assert(id / h == 0);
    return;
  };

  int sx = -1, sy = -1, sd = -1, gx = -1, gy = -1, gd = -1;
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      if (f[i][j] == 'K') {
        sx = i, sy = j;
        for (int d = 0; d < 4; d++) {
          int ni = i + dx[d], nj = j + dy[d];
          if (!out_of_borders(ni, nj) && f[ni][nj] != '#') sd = d;
        }
      }
      if (f[i][j] == 'M') {
        gx = i, gy = j;
        for (int d = 0; d < 4; d++) {
          int ni = i + dx[d], nj = j + dy[d];
          if (!out_of_borders(ni, nj) && f[ni][nj] != '#') gd = d;
        }
      }
    }
  }
  dmp(sx, sy, sd, gx, gy, gd);

  for (int d = 0; d < 4; d++) {
    if (d == sd) continue;
    auto [ssx, ssy] = go[sx][sy][sd];
    int S = encode(ssx, ssy, sd, sx, sy, d);

    vector<int> dist;
    dist.assign(4 * h * w * 4 * h * w, numeric_limits<int>::max());
    dist[S] = 0;
    queue<int> q;
    q.push(S);
    while (!q.empty()) {
      auto v = q.front();
      q.pop();
      int ai, aj, ad, bi, bj, bd;
      decode(v, ai, aj, ad, bi, bj, bd);
      {
        int nai = ai + dx[ad], naj = aj + dy[ad];
        assert(!out_of_borders(nai, naj) && f[nai][naj] == '#');
        int nbi = bi + dx[bd], nbj = bj + dy[bd];
        assert(!out_of_borders(nbi, nbj) && f[nbi][nbj] == '#');
      }
      // turn right and go straight
      {
        int nad = (ad + 1) % 4;
        auto [nai, naj] = go[ai][aj][nad];
        int nbd = (bd + 1) % 4;
        for (auto [nbi, nbj] : rev[bi][bj][bd]) {
          int nnbi = nbi + dx[nbd], nnbj = nbj + dy[nbd];
          assert(!out_of_borders(nnbi, nnbj));
          if (f[nnbi][nnbj] != '#') continue;
          int u = encode(nai, naj, nad, nbi, nbj, nbd);
          if (dist[u] != 0) {
            dist[u] = 0;
            q.push(u);
          }
        }
      }
      // turn left and go straight
      {
        int nad = (ad + 3) % 4;
        auto [nai, naj] = go[ai][aj][nad];
        int nbd = (bd + 3) % 4;
        for (auto [nbi, nbj] : rev[bi][bj][bd]) {
          int nnbi = nbi + dx[nbd], nnbj = nbj + dy[nbd];
          assert(!out_of_borders(nnbi, nnbj));
          if (f[nnbi][nnbj] != '#') continue;
          int u = encode(nai, naj, nad, nbi, nbj, nbd);
          if (dist[u] != 0) {
            dist[u] = 0;
            q.push(u);
          }
        }
      }
    }

    auto [ggx, ggy] = go[gx][gy][gd];
    for (int e = 0; e < 4; e++) {
      int id = encode(gx, gy, e, ggx, ggy, gd);
      if (dist[id] == 0) {
        cout << "He can accomplish his mission." << endl;
        return true;
      }
    }
  }

  {
    auto [ssx, ssy] = go[sx][sy][sd];
    int S = encode(ssx, ssy, sd, 0, 0, 0);
    vector<int> dist;
    dist.assign(4 * h * w * 4 * h * w, numeric_limits<int>::max());
    dist[S] = 0;
    queue<int> q;
    q.push(S);
    while (!q.empty()) {
      auto v = q.front();
      q.pop();
      int ai, aj, ad, bi, bj, bd;
      decode(v, ai, aj, ad, bi, bj, bd);
      {
        int nai = ai + dx[ad], naj = aj + dy[ad];
        assert(!out_of_borders(nai, naj) && f[nai][naj] == '#');
      }
      // turn right and go straight
      {
        int nad = (ad + 1) % 4;
        auto [nai, naj] = go[ai][aj][nad];
        int u = encode(nai, naj, nad, 0, 0, 0);
        if (dist[u] != 0) {
          dist[u] = 0;
          q.push(u);
        }
      }
      // turn left and go straight
      {
        int nad = (ad + 3) % 4;
        auto [nai, naj] = go[ai][aj][nad];
        int u = encode(nai, naj, nad, 0, 0, 0);
        if (dist[u] != 0) {
          dist[u] = 0;
          q.push(u);
        }
      }
    }
    int T = encode(gx, gy, (gd + 2) % 4, 0, 0, 0);
    if (dist[T] == 0) {
      cout << "He cannot return to the kitchen." << endl;
      return true;
    }
  }

  cout << "He cannot bring tea to his master." << endl;
  return true;
}

int main() {
  fastio();
  if (!multitest) {
    while (solve()) {}
  } else {
    cerr << "[Warning] Multi testcase mode on" << endl;
    int t;
    cin >> t;
    while (t--) solve();
  }
  return 0;
}
accuracy: 1
time_ms: 420
memory_kb: 101532
final_rank: 19

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

using namespace std;

#define eps 1e-9
#define INF 2000000000              // 2e9
#define LLINF 2000000000000000000ll // 2e18 (llmax:9e18)
#define all(x) (x).begin(), (x).end()
#define sq(x) ((x) * (x))

#define rep(i, x) for (int i = 0; i < (int)(x); i++)
#define drep(i, x) for (int i = ((int)(x)-1); i >= 0; i--)

#define popcount __builtin_popcount
#define next __next
#define prev __prev

#ifndef LOCAL
#define dmp(...) ;
#else
#define dmp(...)                                                               \
  cerr << "[ " << #__VA_ARGS__ << " ] : " << dump_str(__VA_ARGS__) << endl
#endif

// ---------------- Utility ------------------

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

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

template <class T>
using MaxHeap = priority_queue<T>;

template <class T>
using MinHeap = priority_queue<T, vector<T>, greater<T>>;

template <class T>
vector<T> vect(int len, T elem) {
  return vector<T>(len, elem);
}

// ----------------- Input -------------------

template <class T, class U>
istream &operator>>(istream &is, pair<T, U> &p) {
  return is >> p.first >> p.second;
}

template <class T>
istream &operator>>(istream &is, vector<T> &vec) {
  for (int i = 0; i < vec.size(); i++) is >> vec[i];
  return is;
}

// ----------------- Output ------------------

template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
  return os << p.first << ',' << p.second;
}

template <class T>
ostream &operator<<(ostream &os, const vector<T> &v) {
  for (const T &e : v) os << e << " ";
  return os;
}

template <class T>
ostream &operator<<(ostream &os, const deque<T> &d) {
  for (const T &e : d) os << e << " ";
  return os;
}

template <class T>
ostream &operator<<(ostream &os, const set<T> &s) {
  os << "{ ";
  for (const T &e : s) os << e << " ";
  return os << "}";
}

template <class T, class U>
ostream &operator<<(ostream &os, const map<T, U> &m) {
  os << "{ ";
  for (const auto &[key, val] : m) os << "( " << key << " -> " << val << " ) ";
  return os << "}";
}

template <class TupleTy, size_t... I>
void dump_tuple(ostream &os, const TupleTy t, std::index_sequence<I...>) {
  (..., (os << (I == 0 ? "" : ",") << std::get<I>(t)));
}

template <class... Args>
ostream &operator<<(ostream &os, const tuple<Args...> &t) {
  os << "(";
  dump_tuple(os, t, std::make_index_sequence<sizeof...(Args)>());
  return os << ")";
}

void dump_str_rec(ostringstream &) {}

template <class Head, class... Tail>
void dump_str_rec(ostringstream &oss, Head &&head, Tail &&... tail) {
  oss << ", " << head;
  dump_str_rec(oss, forward<Tail>(tail)...);
}

template <class T, class... U>
string dump_str(T &&arg, U &&... args) {
  ostringstream oss;
  oss << arg;
  dump_str_rec(oss, forward<U>(args)...);
  return oss.str();
}

// --------------- Fast I/O ------------------

void fastio() {
  cin.tie(0);
  ios::sync_with_stdio(0);
  cout << fixed << setprecision(20);
}

// ------------------ ACL --------------------

// #include <atcoder/modint>
// constexpr int MOD = 998244353;
// constexpr int MOD = 1000000007;
// using mint = atcoder::static_modint<MOD>;
// ostream &operator<<(ostream &os, const mint &v) {
//   return os << v.val();
// }

// ------------ End of template --------------

#define endl "\n"
using ll = long long;
using pii = pair<int, int>;

const bool multitest = false;

struct Graph {
  int V;
  vector<vector<int>> G;
  Graph() {}
  Graph(int V) : V(V) { G.resize(V); }
  void add_edge(int a, int b) { G[a].push_back(b); }
  size_t size() const { return G.size(); }
  const vector<int> &operator[](int id) const { return G[id]; }
};

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

bool solve() {
  int h, w;
  cin >> w >> h;

  if (h == 0 && w == 0) return false;

  vector<string> f(h);
  cin >> f;

  auto out_of_borders = [&](int x, int y) {
    return (x < 0 || x >= h || y < 0 || y >= w);
  };

  auto go = vect(h, vect(w, vect(4, pii(-1, -1))));
  auto rev = vect(h, vect(w, vect(4, vector<pii>())));
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      if (f[i][j] == '#') continue;
      for (int d = 0; d < 4; d++) {
        int x = i, y = j;
        while (!out_of_borders(x + dx[d], y + dy[d]) &&
               f[x + dx[d]][y + dy[d]] != '#') {
          x += dx[d];
          y += dy[d];
        }
        go[i][j][d] = pii(x, y);
        rev[x][y][d].emplace_back(i, j);
      }
    }
  }

  auto encode = [&](int ax, int ay, int ad, int bx, int by, int bd) {
    return (4 * w * ax + 4 * ay + ad) * 4 * w * h + (4 * w * bx + 4 * by + bd);
  };

  auto decode = [&](int id, int &ax, int &ay, int &ad, int &bx, int &by,
                    int &bd) {
    bd = id % 4, id /= 4;
    by = id % w, id /= w;
    bx = id % h, id /= h;
    ad = id % 4, id /= 4;
    ay = id % w, id /= w;
    ax = id % h, assert(id / h == 0);
    return;
  };

  int sx = -1, sy = -1, sd = -1, gx = -1, gy = -1, gd = -1;
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      if (f[i][j] == 'K') {
        sx = i, sy = j;
        for (int d = 0; d < 4; d++) {
          int ni = i + dx[d], nj = j + dy[d];
          if (!out_of_borders(ni, nj) && f[ni][nj] != '#') sd = d;
        }
      }
      if (f[i][j] == 'M') {
        gx = i, gy = j;
        for (int d = 0; d < 4; d++) {
          int ni = i + dx[d], nj = j + dy[d];
          if (!out_of_borders(ni, nj) && f[ni][nj] != '#') gd = d;
        }
      }
    }
  }
  dmp(sx, sy, sd, gx, gy, gd);

  // Graph g(4 * h * w * 4 * h * w);
  // for (int ai = 0; ai < h; ai++) {
  //   for (int aj = 0; aj < w; aj++) {
  //     for (int ad = 0; ad < 4; ad++) {
  //       for (int bi = 0; bi < h; bi++) {
  //         for (int bj = 0; bj < w; bj++) {
  //           for (int bd = 0; bd < 4; bd++) {
  //             int u = encode(ai, aj, ad, bi, bj, bd);
  //             // turn right
  //             {
  //               int nad = (ad + 1) % 4;
  //               auto [nai, naj] = go[ai][aj][nad];
  //               int nbd = (bd + 1) % 4;
  //               for (auto [nbi, nbj] : rev[bi][bj][bd]) {
  //                 int v = encode(nai, naj, nad, nbi, nbj, nbd);
  //                 g.add_edge(u, v);
  //               }
  //             }
  //             // turn left
  //             {
  //               int nad = (ad + 3) % 4;
  //               auto [nai, naj] = go[ai][aj][nad];
  //               int nbd = (bd + 3) % 4;
  //               for (auto [nbi, nbj] : rev[bi][bj][bd]) {
  //                 int v = encode(nai, naj, nad, nbi, nbj, nbd);
  //                 g.add_edge(u, v);
  //               }
  //             }
  //           }
  //         }
  //       }
  //     }
  //   }
  // }

  for (int d = 0; d < 4; d++) {
    if (d == sd) continue;
    auto [ssx, ssy] = go[sx][sy][sd];
    int S = encode(ssx, ssy, sd, sx, sy, d);

    vector<int> dist;
    dist.assign(4 * h * w * 4 * h * w, numeric_limits<int>::max());
    dist[S] = 0;
    queue<int> q;
    q.push(S);
    while (!q.empty()) {
      auto v = q.front();
      q.pop();
      int ai, aj, ad, bi, bj, bd;
      decode(v, ai, aj, ad, bi, bj, bd);
      {
        int nai = ai + dx[ad], naj = aj + dy[ad];
        assert(!out_of_borders(nai, naj) && f[nai][naj] == '#');
        int nbi = bi + dx[bd], nbj = bj + dy[bd];
        assert(!out_of_borders(nbi, nbj) && f[nbi][nbj] == '#');
      }
      // turn right and go straight
      {
        int nad = (ad + 1) % 4;
        auto [nai, naj] = go[ai][aj][nad];
        int nbd = (bd + 1) % 4;
        for (auto [nbi, nbj] : rev[bi][bj][bd]) {
          int nnbi = nbi + dx[nbd], nnbj = nbj + dy[nbd];
          assert(!out_of_borders(nnbi, nnbj));
          if (f[nnbi][nnbj] != '#') continue;
          int u = encode(nai, naj, nad, nbi, nbj, nbd);
          if (dist[u] != 0) {
            dist[u] = 0;
            q.push(u);
          }
        }
      }
      // turn left and go straight
      {
        int nad = (ad + 3) % 4;
        auto [nai, naj] = go[ai][aj][nad];
        int nbd = (bd + 3) % 4;
        for (auto [nbi, nbj] : rev[bi][bj][bd]) {
          int nnbi = nbi + dx[nbd], nnbj = nbj + dy[nbd];
          assert(!out_of_borders(nnbi, nnbj));
          if (f[nnbi][nnbj] != '#') continue;
          int u = encode(nai, naj, nad, nbi, nbj, nbd);
          if (dist[u] != 0) {
            dist[u] = 0;
            q.push(u);
          }
        }
      }
    }

    auto [ggx, ggy] = go[gx][gy][gd];
    for (int e = 0; e < 4; e++) {
      int id = encode(gx, gy, e, ggx, ggy, gd);
      if (dist[id] == 0) {
        cout << "He can accomplish his mission." << endl;
        return true;
      }
    }
  }

  {
    auto [ssx, ssy] = go[sx][sy][sd];
    int S = encode(ssx, ssy, sd, 0, 0, 0);
    vector<int> dist;
    dist.assign(4 * h * w * 4 * h * w, numeric_limits<int>::max());
    dist[S] = 0;
    queue<int> q;
    q.push(S);
    while (!q.empty()) {
      auto v = q.front();
      q.pop();
      int ai, aj, ad, bi, bj, bd;
      decode(v, ai, aj, ad, bi, bj, bd);
      {
        int nai = ai + dx[ad], naj = aj + dy[ad];
        assert(!out_of_borders(nai, naj) && f[nai][naj] == '#');
      }
      // turn right and go straight
      {
        int nad = (ad + 1) % 4;
        auto [nai, naj] = go[ai][aj][nad];
        int u = encode(nai, naj, nad, 0, 0, 0);
        if (dist[u] != 0) {
          dist[u] = 0;
          q.push(u);
        }
      }
      // turn left and go straight
      {
        int nad = (ad + 3) % 4;
        auto [nai, naj] = go[ai][aj][nad];
        int u = encode(nai, naj, nad, 0, 0, 0);
        if (dist[u] != 0) {
          dist[u] = 0;
          q.push(u);
        }
      }
    }
    int T = encode(gx, gy, (gd + 2) % 4, 0, 0, 0);
    if (dist[T] == 0) {
      cout << "He cannot return to the kitchen." << endl;
      return true;
    }
  }

  cout << "He cannot bring tea to his master." << endl;
  return true;
}

int main() {
  fastio();
  if (!multitest) {
    while (solve()) {}
  } else {
    cerr << "[Warning] Multi testcase mode on" << endl;
    int t;
    cin >> t;
    while (t--) solve();
  }
  return 0;
}
accuracy: 1
time_ms: 410
memory_kb: 101396
final_rank: 18

code_snippet: /*	author:  Kite_kuma
	created: 2021.10.21 18:34:32 */

// #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, 1, -1, -1, 1};
int dy[8] = {0, 1, 0, -1, 1, 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

int cnt = 0;
string accomplish = "He can accomplish his mission.";
string can_master_cannot_kitchen = "He cannot return to the kitchen.";
string cannot_bring = "He cannot bring tea to his master.";

string solve(int w) {
	int h;
	cin >> h;

	VEC(string, s, h);

	int kx, ky, mx, my;
	rep(i, h) rep(j, w) {
		if(s[i][j] == 'K') {
			kx = i;
			ky = j;
		} else if(s[i][j] == 'M') {
			mx = i;
			my = j;
		}
	}

	auto wall = [&s](int x, int y) { return s[x][y] == '#'; };

	using state = tuple<int, int, int, int, int, int>;

	queue<state> q;
	set<state> se;

	rep(i, 4) rep(j, 4) {
		if(wall(kx + dx[i], ky + dy[i])) continue;
		state st(kx, ky, kx, ky, i, j);
		q.push(st);
		se.insert(st);
	}

	// after change his direction, before move foward

	auto add_state = [&q, &se](int gx, int gy, int tx, int ty, int gdir, int tdir) {
		state st(gx, gy, tx, ty, gdir, tdir);
		if(!se.count(st)) {
			se.insert(st);
			q.push(st);
		}
		return;
	};

	debug(s);

	while(!q.empty()) {
		int gx, gy, tx, ty, gdir, tdir;
		tie(gx, gy, tx, ty, gdir, tdir) = q.front();
		q.pop();

		if(cnt == 8) debug(gx, gy, tx, ty, gdir, tdir);

		int tback = (tdir + 2) % 4;
		{
			int tbx, tby;
			tbx = tx + dx[tback];
			tby = ty + dy[tback];
			if(!wall(tbx, tby)) continue;
		}

		while(!wall(gx + dx[gdir], gy + dy[gdir])) {
			gx += dx[gdir];
			gy += dy[gdir];
		}

		while(!wall(tx, ty)) {
			if(gx == mx && gy == my) {
				if(tx == mx && ty == my && !wall(mx + dx[tback], my + dy[tback])) {
					return accomplish;
				}
			}
			add_state(gx, gy, tx, ty, (gdir + 1) % 4, (tdir + 1) % 4);
			add_state(gx, gy, tx, ty, (gdir + 3) % 4, (tdir + 3) % 4);
			tx += dx[tdir];
			ty += dy[tdir];
		}
	}

	se.clear();

	rep(i, 4) {
		if(wall(kx + dx[i], ky + dy[i])) continue;
		state st(kx, ky, kx, ky, i, i);
		add_state(kx, ky, kx, ky, i, i);
	}

	while(!q.empty()) {
		int gx, gy, tx, ty, gdir, tdir;
		tie(gx, gy, ignore, ignore, gdir, ignore) = q.front();
		q.pop();

		if(cnt == 8) debug(gx, gy, tx, ty, gdir, tdir);

		// int tback = (tdir + 2) % 4;
		// {
		// 	int tbx, tby;
		// 	tbx = tx + dx[tback];
		// 	tby = ty + dy[tback];
		// 	if(!wall(tbx, tby)) continue;
		// }

		while(!wall(gx + dx[gdir], gy + dy[gdir])) {
			gx += dx[gdir];
			gy += dy[gdir];
		}

		// while(!wall(tx, ty)) {
		if(gx == mx && gy == my) return can_master_cannot_kitchen;
		// 		if(tx == mx && ty == my && !wall(mx + dx[tback], my + dy[tback])) {
		// 			return accomplish;
		// 		}
		// 	}
		add_state(gx, gy, 0, 0, (gdir + 1) % 4, 0);
		add_state(gx, gy, 0, 0, (gdir + 3) % 4, 0);
		// 	tx += dx[tdir];
		// 	ty += dy[tdir];
		// }
	}

	return cannot_bring;
}

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

	int n;
	while(cin >> n && n) {
		cnt++;
		cout << solve(n) << dl;
	}
	return 0;
}
accuracy: 1
time_ms: 3700
memory_kb: 47216
final_rank: 20

code_snippet: #include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<vector>
#include<cmath>
#include<algorithm>
#include<map>
#include<queue>
#include<deque>
#include<iomanip>
#include<tuple>
#include<cassert>
#include<set>
#include<complex>
#include<numeric>
#include<functional>
#include<unordered_map>
#include<unordered_set>
using namespace std;
typedef long long int LL;
typedef pair<int,int> P;
typedef pair<LL,LL> LP;
const int INF=1<<30;
const LL MAX=1e9+7;

void array_show(int *array,int array_n,char middle=' '){
	for(int i=0;i<array_n;i++)printf("%d%c",array[i],(i!=array_n-1?middle:'\n'));
}
void array_show(LL *array,int array_n,char middle=' '){
	for(int i=0;i<array_n;i++)printf("%lld%c",array[i],(i!=array_n-1?middle:'\n'));
}
void array_show(vector<int> &vec_s,int vec_n=-1,char middle=' '){
	if(vec_n==-1)vec_n=vec_s.size();
	for(int i=0;i<vec_n;i++)printf("%d%c",vec_s[i],(i!=vec_n-1?middle:'\n'));
}
void array_show(vector<LL> &vec_s,int vec_n=-1,char middle=' '){
	if(vec_n==-1)vec_n=vec_s.size();
	for(int i=0;i<vec_n;i++)printf("%lld%c",vec_s[i],(i!=vec_n-1?middle:'\n'));
}
template<typename T> ostream& operator<<(ostream& os,const vector<T>& v1){
	int n=v1.size();
	for(int i=0;i<n;i++){
		if(i)os<<" ";
		os<<v1[i];
	}
	return os;
}
template<typename T1,typename T2> ostream& operator<<(ostream& os,const pair<T1,T2>& p){
	os<<p.first<<" "<<p.second;
	return os;
}
template<typename T> istream& operator>>(istream& is,vector<T>& v1){
	int n=v1.size();
	for(int i=0;i<n;i++)is>>v1[i];
	return is;
}
template<typename T1,typename T2> istream& operator>>(istream& is,pair<T1,T2>& p){
	is>>p.first>>p.second;
	return is;
}

int n,m;
namespace sol{
	typedef vector<char> V1;
	typedef vector<V1> V2;
	typedef vector<V2> V3;
	typedef vector<V3> V4;
	typedef vector<V4> V5;
	typedef vector<V5> V6;
	const int move[4][2]={{1,0},{0,1},{-1,0},{0,-1}};

	int check_to(int x,int y,vector<string>& grid){
		for(int i=0;i<4;i++){
			if(grid[x+move[i][0]][y+move[i][1]]!='#')return i;
		}
		assert(false);
		return -1;
	}
	bool dp[16][64][16][64][4][4];

	void solve(){
		int i,j,k;
		int a,b,c,d,e;
		int x,y;
		int p,q;
		int sto,eto;
		int sx,sy,ex,ey;
		vector<string> grid(n);
		cin>>grid;
		V3 tx(n,V2(m,V1(4)));
		V3 ty(n,V2(m,V1(4)));
		memset(dp,false,sizeof(dp));
		for(i=0;i<n;i++){
			for(j=0;j<m;j++){
				for(k=0;k<4;k++){
					x=i,y=j;
					for(;grid[x][y]!='#';x+=move[k][0],y+=move[k][1]);
					x-=move[k][0],y-=move[k][1];
					tx[i][j][k]=x;
					ty[i][j][k]=y;
				}
				if(grid[i][j]=='K'){
					sto=check_to(i,j,grid);
					sx=i,sy=j;
				}
				if(grid[i][j]=='M'){
					eto=check_to(i,j,grid);
					ex=i,ey=j;
				}
			}
		}
		queue<tuple<int,int,int,int,int,int>> q1;
		for(i=0;i<4;i++){
			x=tx[sx][sy][sto],y=ty[sx][sy][sto];
			dp[x][y][sx][sy][sto][i]=true;
			q1.push({x,y,sx,sy,sto,i});
		}
		while(!q1.empty()){
			tie(x,y,a,b,c,d)=q1.front(),q1.pop();
			p=a+move[d][0],q=b+move[d][1];
			if(grid[p][q]!='#' && !dp[x][y][p][q][c][d]){
				dp[x][y][p][q][c][d]=true;
				q1.push({x,y,p,q,c,d});
			}
			auto func=[&](int g,int h) -> void{
				g=(g+4)%4,h=(h+4)%4;
				e=(h+2)%4;
				p=a+move[e][0],q=b+move[e][1];
				if(grid[p][q]!='#')return;
				p=tx[x][y][g],q=ty[x][y][g];
				if(!dp[p][q][a][b][g][h]){
					dp[p][q][a][b][g][h]=true;
					q1.push({p,q,a,b,g,h});
				}
			};
			func(c+1,d+1);
			func(c-1,d-1);
		}
		for(i=0;i<4;i++){
			j=(eto+2)%4;
			if(dp[ex][ey][ex][ey][i][j]){
				cout<<"He can accomplish his mission."<<endl;
				return;
			}
		}
		
		V3 dp2(n,V2(m,V1(4)));
		queue<tuple<int,int,int>> q2;
		dp2[sx][sy][sto]=1;
		q2.push({sx,sy,sto});
		while(!q2.empty()){
			tie(a,b,c)=q2.front(),q2.pop();
			for(i=-1;i<=1;i+=2){
				d=(c+i+4)%4;
				x=tx[a][b][d],y=ty[a][b][d];
				if(dp2[x][y][d]==0){
					dp2[x][y][d]=1;
					q2.push({x,y,d});
				}
			}
		}
		for(i=0;i<4;i++){
			if(dp2[ex][ey][i]){
				cout<<"He cannot return to the kitchen."<<endl;
				return;
			}
		}
		cout<<"He cannot bring tea to his master."<<endl;
	}
}

int main(){
	cin.tie(0);
	ios::sync_with_stdio(false);
	while(cin>>m>>n){
		if(n==0 && m==0)return 0;
		sol::solve();
	}
}
accuracy: 1
time_ms: 330
memory_kb: 20240
final_rank: 5

code_snippet: #include <bits/stdc++.h>
using namespace std;
vector<int> dx = {1, 0, -1, 0};
vector<int> dy = {0, 1, 0, -1};
int main(){
  while (true){
    int W, H;
    cin >> W >> H;
    if (W == 0 && H == 0){
      break;
    }
    vector<vector<char>> c(H, vector<char>(W));
    for (int i = 0; i < H; i++){
      for (int j = 0; j < W; j++){
        cin >> c[i][j];
      }
    }
    vector<vector<int>> id(H, vector<int>(W));
    vector<int> X, Y;
    int cnt = 0;
    for (int i = 0; i < H; i++){
      for (int j = 0; j < W; j++){
        if (c[i][j] != '#'){
          id[i][j] = cnt;
          X.push_back(i);
          Y.push_back(j);
          cnt++;
        }
      }
    }
    int K, M;
    for (int i = 0; i < cnt; i++){
      if (c[X[i]][Y[i]] == 'K'){
        K = i;
      }
      if (c[X[i]][Y[i]] == 'M'){
        M = i;
      }
    }
    int s = 0;
    for (int i = 0; i < 4; i++){
      if (c[X[K] + dx[i]][Y[K] + dy[i]] == '.'){
        s = i;
      }
    }
    int t = 0;
    for (int i = 0; i < 4; i++){
      if (c[X[M] + dx[i]][Y[M] + dy[i]] == '.'){
        t = i;
      }
    }
    vector<vector<vector<vector<bool>>>> used(4, vector<vector<vector<bool>>>(4, vector<vector<bool>>(cnt + 1, vector<bool>(cnt, false))));
    queue<tuple<int, int, int, int>> Q;
    for (int i = 0; i < 4; i++){
      used[s][i][K][K] = true;
      Q.push(make_tuple(s, i, K, K));
    }
    bool ok1 = false, ok2 = false;
    while (!Q.empty()){
      int d1 = get<0>(Q.front());
      int d2 = get<1>(Q.front());
      int v1 = get<2>(Q.front());
      int v2 = get<3>(Q.front());
      Q.pop();
      int x1 = X[v1];
      int y1 = Y[v1];
      while (c[x1 + dx[d1]][y1 + dy[d1]] != '#'){
        x1 += dx[d1];
        y1 += dy[d1];
      }
      if (id[x1][y1] == M){
        ok2 = true;
      }
      int d1l = (d1 + 1) % 4;
      int d1r = (d1 + 3) % 4;
      if (!used[d1l][0][id[x1][y1]][cnt]){
        used[d1l][0][id[x1][y1]][cnt] = true;
        Q.push(make_tuple(d1l, 0, id[x1][y1], cnt));
      }
      if (!used[d1r][0][id[x1][y1]][cnt]){
        used[d1r][0][id[x1][y1]][cnt] = true;
        Q.push(make_tuple(d1r, 0, id[x1][y1], cnt));
      }
      if (v2 != cnt){
        int x2 = X[v2];
        int y2 = Y[v2];
        int d2l = (d2 + 1) % 4;
        int d2r = (d2 + 3) % 4;
        while (true){
          if (c[x2 + dx[d2r]][y2 + dy[d2r]] == '#'){
            if (id[x1][y1] == M && id[x2][y2] == M && d2 == (t ^ 2)){
              ok1 = true;
            }
            if (!used[d1l][d2l][id[x1][y1]][id[x2][y2]]){
              used[d1l][d2l][id[x1][y1]][id[x2][y2]] = true;
              Q.push(make_tuple(d1l, d2l, id[x1][y1], id[x2][y2]));
            }
          }
          if (c[x2 + dx[d2l]][y2 + dy[d2l]] == '#'){
            if (id[x1][y1] == M && id[x2][y2] == M && d2 == (t ^ 2)){
              ok1 = true;
            }
            if (!used[d1r][d2r][id[x1][y1]][id[x2][y2]]){
              used[d1r][d2r][id[x1][y1]][id[x2][y2]] = true;
              Q.push(make_tuple(d1r, d2r, id[x1][y1], id[x2][y2]));
            }
          }
          if (c[x2 + dx[d2]][y2 + dy[d2]] == '#'){
            break;
          }
          x2 += dx[d2];
          y2 += dy[d2];
        }
      }
    }
    if (ok1){
      cout << "He can accomplish his mission." << endl;
    } else if (ok2){
      cout << "He cannot return to the kitchen." << endl;
    } else {
      cout << "He cannot bring tea to his master." << endl;
    }
  }
}
accuracy: 1
time_ms: 360
memory_kb: 6368
final_rank: 2

code_snippet: #include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};

char grid[16][64];
bool used[16][64][4][16][64][4];
vector<string> output{
    "He can accomplish his mission.",
    "He cannot return to the kitchen.",
    "He cannot bring tea to his master.",
};

void dfs(int fy, int fx, int fd, int ry, int rx, int rd){
    if(used[fy][fx][fd][ry][rx][rd]) return;
    used[fy][fx][fd][ry][rx][rd] = true;
    for(int diff=1; diff<=3; diff+=2){
        int nfy = fy;
        int nfx = fx;
        int nfd = (fd +diff) %4;
        while(grid[nfy+dy[nfd]][nfx+dx[nfd]] != '#'){
            nfy += dy[nfd];
            nfx += dx[nfd];
        }
        if(ry == 0){
            dfs(nfy, nfx, nfd, 0, 0, 0);
            continue;
        }
        int nry = ry;
        int nrx = rx;
        int nrd = (rd +diff) %4;
        while(grid[nry][nrx] != '#'){
            if(grid[nry+dy[nrd]][nrx+dx[nrd]] == '#'){
                dfs(nfy, nfx, nfd, nry, nrx, nrd);
            }
            nry -= dy[rd];
            nrx -= dx[rd];
        }
    }
}

int main(){
    while(1){
        int w,h;
        cin >> w >> h;
        if(w == 0) break;

        memset(used, 0, sizeof(used));
        int sy,sx,gy,gx;
        sy = sx = gy = gx = -1;
        for(int i=0; i<h; i++){
            for(int j=0; j<w; j++){
                cin >> grid[i][j];
                if(grid[i][j] == 'K'){
                    sy = i;
                    sx = j;
                }
                if(grid[i][j] == 'M'){
                    gy = i;
                    gx = j;
                }
            }
        }

        int dir_go=-1, dir_ret=-1;
        for(int d=0; d<4; d++){
            if(grid[sy+dy[d]][sx+dx[d]] != '#'){
                dir_go = d;
            }
            if(grid[gy+dy[d]][gx+dx[d]] != '#'){
                dir_ret = d;
            }
        }
        int fsy = sy;
        int fsx = sx;
        while(grid[fsy+dy[dir_go]][fsx+dx[dir_go]] != '#'){
            fsy += dy[dir_go];
            fsx += dx[dir_go];
        }
        int fgy = gy;
        int fgx = gx;
        while(grid[fgy+dy[dir_ret]][fgx+dx[dir_ret]] != '#'){
            fgy += dy[dir_ret];
            fgx += dx[dir_ret];
        }
        
        dfs(fsy, fsx, dir_go, sy, sx, (dir_go+1)%4);
        dfs(fsy, fsx, dir_go, sy, sx, (dir_go+2)%4);
        dfs(fsy, fsx, dir_go, sy, sx, (dir_go+3)%4);
        dfs(fsy, fsx, dir_go, 0, 0, 0);
        bool ok = false;
        for(int i=0; i<4; i++){
            if(used[gy][gx][i][fgy][fgx][dir_ret]){
                ok = true;
            }
        }
        if(ok){
            cout << output[0] << endl;
            continue;
        }
        if(used[gy][gx][(dir_ret+2)%4][0][0][0]){
            cout << output[1] << endl;
        }else{
            cout << output[2] << endl;
        }
    }
    return 0;
}
accuracy: 1
time_ms: 290
memory_kb: 20092
final_rank: 4

code_snippet: #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<utility>
#include<cassert>
#include<complex>
#include<numeric>
using namespace std;

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

typedef unsigned long long ul;
typedef unsigned int ui;
const ll mod = 1000000007;
const ll INF = (1e+18) + 7;
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-6;
const ld pi = acos(-1.0);
//typedef vector<vector<ll>> mat;
typedef vector<int> vec;

ll mod_pow(ll a, ll n) {
	ll res = 1;
	while (n) {
		if (n & 1)res = res * a%mod;
		a = a * a%mod; 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, int 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)); }

const int max_n = 2000500;
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];
}

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

int w, h;
char mp[16][64];
bool exi[16][64][4][16][64][4];

bool canr[16][64][4];
struct status {
	int x1, y1, d1, x2, y2, d2;
};
void solve() {
	rep(i, h)rep(j, w) {
		cin >> mp[i][j];
	}
	rep(i, h)rep(j, w)rep(k, 4)rep(x, h)rep(y, w)rep(l, 4) {
		exi[i][j][k][x][y][l] = false;
	}
	queue<status> q;
	rep(i, h)rep(j, w)if (mp[i][j] == 'K') {
		int d = 0;
		rep(k, 4) {
			int nx = i + dx[k];
			int ny = j + dy[k];
			if (mp[nx][ny] != '#') {
				d = k;
			}
		}
		rep(k, 4) {
			if (k == (2^d))continue;
			exi[i][j][d][i][j][k] = true;
			q.push({ i,j,d,i,j,k });
		}
	}
	while (!q.empty()) {
		status s = q.front(); q.pop();
		int x1 = s.x1;
		int y1 = s.y1;
		int d1 = s.d1;
		/*if (s.x1 == 6 && s.y1 == 10) {
			cout << s.d1 << endl;
		}*/
		/*if (s.x2 == 4 && s.y2 == 5 && s.d2 == 3) {
			cout << s.x1 << " " << s.y1 << " " << s.d1 << endl;
		}*/
		//cout << s.x1 << " " << s.y1 << " " << s.d1 << endl;
		//cout << s.x1 << " " << s.y1 << " " << s.d1 << " " << s.x2 << " " << s.y2 << " " << s.d2 << endl;
		while (mp[x1 + dx[d1]][y1 + dy[d1]] != '#') {
			x1 += dx[d1]; y1 += dy[d1];
		}
		int x2 = s.x2;
		int y2 = s.y2;
		int d2 = s.d2;
		//assert(mp[x1][y1] != '#');
		//assert(mp[x2][y2] != '#');
		while (mp[x2][y2] != '#') {
			//turn right
			int dd1 = (d1 + 1) % 4;
			int dd2 = (d2 + 1) % 4;
			if (mp[x2 + dx[dd2 ^ 2]][y2 + dy[dd2 ^ 2]] == '#') {
				if (!exi[x1][y1][dd1][x2][y2][dd2]) {
					exi[x1][y1][dd1][x2][y2][dd2] = true;
					q.push({ x1,y1,dd1,x2,y2,dd2 });
				}
			}
			//turn left
			dd1 = (d1 + 3) % 4;
			dd2 = (d2 + 3) % 4;
			if (mp[x2 + dx[dd2 ^ 2]][y2 + dy[dd2 ^ 2]] == '#') {
				if (!exi[x1][y1][dd1][x2][y2][dd2]) {
					exi[x1][y1][dd1][x2][y2][dd2] = true;
					q.push({ x1,y1,dd1,x2,y2,dd2 });
				}
			}

			x2 += dx[d2];
			y2 += dy[d2];
		}
	}
	int gx, gy;
	int gd = 0;
	rep(i, h)rep(j, w) {
		if (mp[i][j] == 'M') {
			gx = i, gy = j;
			rep(k, 4) {
				if (mp[i + dx[k]][j + dy[k]] != '#') {
					gd = k;
				}
			}
		}
	}
	vector<status> vf,vs;
	rep(k, 4) {
		int cx = gx, cy = gy;
		while (mp[cx][cy] != '#') {
			vf.push_back({ cx,cy,k ^ 2,0,0,0 });
			/*if (k == gd) {
				vs.push_back({ 0,0,0,cx,cy , k ^ 2 });
			}*/

			cx += dx[k];
			cy += dy[k];
		}
		cx -= dx[k]; cy -= dy[k];
		if (k == gd) {
			vs.push_back({ 0,0,0,cx,cy,k ^ 2 });
		}
	}
	for (status s2 : vs) {
		//cout << s2.x2 << " " << s2.y2 << " " << s2.d2 << endl;
	}
	for (status s1 : vf)for (status s2 : vs) {
		if (exi[s1.x1][s1.y1][s1.d1][s2.x2][s2.y2][s2.d2]) {
			cout << "He can accomplish his mission." << endl;
			return;
		}
	}
	rep(i, h)rep(j, w)rep(k, 4) {
		canr[i][j][k] = false;
	}
	rep(i, h)rep(j, w){
		if (mp[i][j] == 'K') {
			int d = 0;
			rep(k, 4) {
				int nx = i + dx[k];
				int ny = j + dy[k];
				if (mp[nx][ny] != '#')d = k;
			}
			canr[i][j][d] = true;
			q.push({ i,j,d });
		}
	}
	while (!q.empty()) {
		status s = q.front(); q.pop();
		int x = s.x1;
		int y = s.y1;
		int d = s.d1;
		while (mp[x + dx[d]][y + dy[d]] != '#') {
			x += dx[d];
			y += dy[d];
		}
		int dd = (d + 1) % 4;
		if (!canr[x][y][dd]) {
			canr[x][y][dd] = true;
			q.push({ x,y,dd });
		}
		dd = (d + 3) % 4;
		if (!canr[x][y][dd]) {
			canr[x][y][dd] = true;
			q.push({ x,y,dd });
		}
	}
	if (canr[gx][gy][gd ^ 1] || canr[gx][gy][gd ^ 3]) {
		cout << "He cannot return to the kitchen." << endl;
		return;
	}
	cout << "He cannot bring tea to his master." << endl;
}


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

code_snippet: #include<bits/stdc++.h>
using namespace std;
using Int = long long;
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;}
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;}

//INSERT ABOVE HERE
const int D = 4,H = 16, W = 64;
bool dp[D][H][W][D][H][W];
char st[H][W];

bool rc[D][H][W];

using P = pair<int, int>;
using T = tuple<int, int, int>;
P mv[D][H][W];

struct ST{
  int k1,y1,x1,k2,y2,x2;
  ST(){}
  ST(int k1,int y1,int x1,int k2,int y2,int x2):
    k1(k1),y1(y1),x1(x1),k2(k2),y2(y2),x2(x2){}
};

signed main(){
  int w,h;
  while(cin>>w>>h,w){
    vector<string> tt(h);
    for(int i=0;i<h;i++) cin>>tt[i];
    memset(st,'#',sizeof(st));
    for(int i=0;i<h;i++)
      for(int j=0;j<w;j++)
        st[i][j]=tt[i][j];
    h=H;w=W;

    int sy=-1,sx=-1,gy=-1,gx=-1;
    for(int i=0;i<h;i++){
      for(int j=0;j<w;j++){
        if(st[i][j]=='K') sy=i,sx=j;
        if(st[i][j]=='M') gy=i,gx=j;
      }
    }

    int dy[]={0,1,0,-1};
    int dx[]={1,0,-1,0};
    for(int i=0;i<h;i++){
      for(int j=0;j<w;j++){
        if(st[i][j]=='#') continue;
        for(int k=0;k<4;k++){
          int y=i,x=j;
          while(st[y+dy[k]][x+dx[k]]!='#'){
            y+=dy[k];
            x+=dx[k];
          }
          mv[k][i][j]=P(y,x);
        }
      }
    }

    {
      memset(rc,0,sizeof(rc));
      queue<T> que;
      for(int k=0;k<4;k++){
        if(st[sy+dy[k]][sx+dx[k]]=='.'){
          int y,x;
          tie(y,x)=mv[k][sy][sx];
          rc[k][y][x]=1;
          que.emplace(k,y,x);
        }
      }

      while(!que.empty()){
        int k,y,x;
        tie(k,y,x)=que.front();que.pop();
        assert(st[y+dy[k]][x+dx[k]]=='#');
        for(int dk=1;dk<4;dk+=2){
          int nk=(k+dk)%4;
          int ny,nx;
          tie(ny,nx)=mv[nk][y][x];
          if(rc[nk][ny][nx]) continue;
          rc[nk][ny][nx]=1;
          que.emplace(nk,ny,nx);
        }
      }

      int flg=0;
      for(int k=0;k<4;k++)
        flg|=rc[k][gy][gx];
      if(!flg){
        cout<<"He cannot bring tea to his master."<<endl;
        continue;
      }
    }

    int tap=0,uku=0;
    for(int k=0;k<4;k++){
      if(st[sy+dy[k]][sx+dx[k]]=='.')
        tap=k;
      if(st[gy+dy[k]][gx+dx[k]]=='.')
        uku=k;
    }
    memset(dp,0,sizeof(dp));
    queue<ST> que;
    auto push=
      [&](int k1,int y1,int x1,int k2,int y2,int x2){
        if(dp[k1][y1][x1][k2][y2][x2]) return;
        dp[k1][y1][x1][k2][y2][x2]=1;
        que.emplace(k1,y1,x1,k2,y2,x2);
      };

    for(int k=0;k<4;k++){
      if(st[sy+dy[k]][sx+dx[k]]!='#') continue;
      push(tap,mv[tap][sy][sx].first,mv[tap][sy][sx].second,k,sy,sx);
    }

    while(!que.empty()){
      ST s=que.front();que.pop();
      assert(st[s.y1][s.x1]!='#');
      assert(st[s.y2][s.x2]!='#');
      assert(st[s.y1+dy[s.k1]][s.x1+dx[s.k1]]=='#');
      assert(st[s.y2+dy[s.k2]][s.x2+dx[s.k2]]=='#');

      for(int dk=1;dk<4;dk+=2){
        int nk1=(s.k1+dk)%4;
        int ny1,nx1;
        tie(ny1,nx1)=mv[nk1][s.y1][s.x1];

        int nk2=(s.k2+dk)%4;
        int ny2=s.y2,nx2=s.x2;
        while(st[ny2][nx2]!='#'){
          if(st[ny2+dy[nk2]][nx2+dx[nk2]]=='#')
            push(nk1,ny1,nx1,nk2,ny2,nx2);
          ny2-=dy[s.k2];
          nx2-=dx[s.k2];
        }
      }
    }

    int flg=0;
    for(int k=0;k<4;k++)
      flg|=dp[k][gy][gx][uku][mv[uku][gy][gx].first][mv[uku][gy][gx].second];
    if(flg) cout<<"He can accomplish his mission."<<endl;
    else cout<<"He cannot return to the kitchen."<<endl;
  }
  return 0;
}
accuracy: 1
time_ms: 240
memory_kb: 19768
final_rank: 3

code_snippet: #include<bits/stdc++.h>
#define inf 1<<29
#define linf (1e16)
#define eps (1e-8)
#define Eps (1e-12)
#define mod 1000000007
#define pi acos(-1.0)
#define phi (1.0+sqrt(5.0))/2.0
#define f first
#define s second
#define mp make_pair
#define pb push_back
#define all(a) (a).begin(),(a).end()
#define pd(a) printf("%.10f\n",(double)(a))
#define pld(a) printf("%.10Lf\n",(ld)(a))
#define FOR(i,a,b) for(int i=(a);i<(b);i++)
#define RFOR(i,a,b) for(int i=(a)-1;(b)<=i;i--)
#define Unique(v) v.erase(unique(all(v)),v.end())
#define equals(a,b) (fabs((a)-(b))<eps)
using namespace std;
typedef long double ld;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<int,double> pid;
typedef pair<double,int> pdi;
typedef pair<double,double> pdd;
typedef vector<int> vi;
typedef vector<pii> vpi;
int dx[4] = {0,1,0,-1};
int dy[4] = {1,0,-1,0};
#define track() cout<<"######"<<endl;

int h,w;
string grid[16];
bool used[16][64][4][16][64][4];
bool flag1,flag2;
int sy,sx,sd,ty,tx,td;

int up(int d){return ((d+0)%4);}
int left(int d){return ((d+1)%4);}
int down(int d){return ((d+2)%4);}
int right(int d){return ((d+3)%4);}

vector<pair<pii,pii> > steps;

void rec(int ky,int kx,int kd,int my,int mx,int md){

  if(used[ky][kx][kd][my][mx][md])return;
  used[ky][kx][kd][my][mx][md] = true;

  int nky=ky,nkx=kx;
  while(1){
    if(grid[nky+dy[kd]][nkx+dx[kd]]=='#')break;
    nky = nky + dy[kd];
    nkx = nkx + dx[kd];
  }
  if(my==0){
    if(nky==ty && nkx==tx)flag1=true;
    rec(nky,nkx,left(kd),0,0,0);
    rec(nky,nkx,right(kd),0,0,0);
    return;
  }

  int nmy=my,nmx=mx; 
  while(1){
    if(grid[nmy+dy[ left(md)  ]][nmx+dx[ left(md)  ]]=='#' &&
       grid[nmy+dy[ right(md) ]][nmx+dx[ right(md) ]]=='.' ){
      rec(nky,nkx,right(kd),nmy,nmx,right(md));
    }
    if(grid[nmy+dy[ right(md) ]][nmx+dx[ right(md) ]]=='#' &&
       grid[nmy+dy[ left(md)  ]][nmx+dx[ left(md)  ]]=='.' ){
      rec(nky,nkx,left(kd),nmy,nmx,left(md));
    }  

    if(grid[nmy+dy[ down(md) ]][nmx+dx[ down(md) ]]=='#'){ 
      if(grid[nmy+dy[ right(md) ]][nmx+dx[ right(md) ]]=='#' &&
         grid[nmy+dy[ left(md)  ]][nmx+dx[ left(md)  ]]=='#' ){
        rec(nky,nkx,right(kd),nmy,nmx,right(md));
        rec(nky,nkx,left(kd),nmy,nmx,left(md));
      }
    }
    
    if(grid[nmy+dy[ md ]][nmx+dx[ md ]]=='#'){ 
      if(grid[nmy+dy[ right(md) ]][nmx+dx[ right(md) ]]=='#' &&
         grid[nmy+dy[ left(md)  ]][nmx+dx[ left(md)  ]]=='#' ){
        rec(nky,nkx,right(kd),nmy,nmx,right(md));
        rec(nky,nkx,left(kd),nmy,nmx,left(md));
      }
      break;
    }
    nmy = nmy + dy[md];
    nmx = nmx + dx[md];
  }
  if(nky==ty && nkx==tx && nmy==ty && nmx==tx && md==(td+2)%4)flag2 = true;
}

string solve(){
  memset(used,0,sizeof(used));
  flag1 = false;
  flag2 = false;
  FOR(i,0,h){
    FOR(j,0,w){
      if(grid[i][j]=='K'){
        sy = i;
        sx = j;
        grid[i][j]='.';
        FOR(k,0,4)
          if(grid[sy+dy[k]][sx+dx[k]]=='.')sd = k;
      }
      if(grid[i][j]=='M'){
        ty = i;
        tx = j;
        grid[i][j]='.';
        FOR(k,0,4)
          if(grid[ty+dy[k]][tx+dx[k]]=='.')td = k;
      }
    }
  }
  FOR(i,0,4)rec(sy,sx,sd,sy,sx,i);
  if(flag2)return "He can accomplish his mission.";
  rec(sy,sx,sd,0,0,0);
  if(flag1)return "He cannot return to the kitchen.";
  return "He cannot bring tea to his master.";
}

int main()
{
  while(cin>>w>>h && w){
    FOR(i,0,h)cin>>grid[i];
    cout<<solve()<<endl;
  }
  return 0;
}
accuracy: 1
time_ms: 460
memory_kb: 20460
final_rank: 8

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

using pii = pair<int, int>;

// direction
// 0: N, 1: E, 2:S, 3:W
constexpr int dx[4] = {0, 1, 0, -1};
constexpr int dy[4] = {-1, 0, 1, 0};
constexpr int dd[2] = {1, 3}; // turn right, left

bool reach1[16][64][4]; // only go to kitchen
bool reach[16][64][4][16][64][4];

int main() {
    int w, h;
    while(cin >> w >> h, w) {
        memset(reach1, false, sizeof(reach1));
        memset(reach, false, sizeof(reach));
        vector<string> v(h);
        for(auto& s : v) cin >> s;

        int sy = -1, sx = -1, sd = -1, gy = -1, gx = -1;
        for(int i = 0; i < h; ++i) {
            for(int j = 0; j < w; ++j) {
                if(v[i][j] == '#') continue;
                if(v[i][j] == 'K') {
                    sy = i, sx = j;
                    for(int d = 0; d < 4; ++d) {
                        if(v[sy + dy[d]][sx + dx[d]] == '#') continue;
                        sd = d;
                    }
                }
                if(v[i][j] == 'M') {
                    gy = i, gx = j;
                }
            }
        }

        function<bool(int, int, int)> go_to_kitchen = [&] (int y, int x, int d) {
            if(reach1[y][x][d]) return false;
            reach1[y][x][d] = true;
            if(y == gy && x == gx) return true;
            bool res = false;
            if(v[y + dy[d]][x + dx[d]] != '#') {
                res = go_to_kitchen(y + dy[d], x + dx[d], d);
            } else {
                res = go_to_kitchen(y, x, (d + 1) % 4);
                res |= go_to_kitchen(y, x, (d + 3) % 4);
            }
            return res;
        };
        function<bool(int, int, int, int, int, int)> dfs = [&] (int y1, int x1, int d1, int y2, int x2, int d2) {
            if(reach[y1][x1][d1][y2][x2][d2]) return false;
            //cout << y1 << ' ' << x1 << ' ' << d1 << ' ' << y2 << ' ' << x2 << ' ' << d2 << endl;
            reach[y1][x1][d1][y2][x2][d2] = true;
            if(gy == y2 && gx == x2 && gy == y1 && gx == x1
               && v[y2 - dy[d2]][x2 - dx[d2]] != '#' && v[y1 + dy[d1]][x1 + dx[d1]] == '#') {
                return true;
            }
            bool res = false;
            if(v[y1 + dy[d1]][x1 + dx[d1]] != '#') {
                res = dfs(y1 + dy[d1], x1 + dx[d1], d1, y2, x2, d2);
            } else { // can turn
                for(int i = 0; i < 2; ++i) {
                    const int nd1 = (d1 + dd[i]) % 4, nd2 = (d2 + dd[i]) % 4;
                    if(v[y2 - dy[nd2]][x2 - dx[nd2]] != '#') continue; // front must be wall
                    res |= dfs(y1, x1, nd1, y2, x2, nd2);
                }
            }
            if(v[y2 + dy[d2]][x2 + dx[d2]] != '#') {
                res |= dfs(y1, x1, d1, y2 + dy[d2], x2 + dx[d2], d2);
            }
            return res;
        };

        bool ac = false;
        for(int d = 0; d < 4; ++d) {
            ac |= dfs(sy, sx, sd, sy, sx, d);
        }

        if(ac) {
            cout << "He can accomplish his mission." << endl;
        } else if(go_to_kitchen(sy, sx, sd)) {
            cout << "He cannot return to the kitchen." << endl;
        } else {
            cout << "He cannot bring tea to his master." << endl;
        }
    }
}
accuracy: 1
time_ms: 950
memory_kb: 25436
final_rank: 11

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

using pii = pair<int, int>;

// direction
// 0: N, 1: E, 2:S, 3:W
constexpr int dx[4] = {0, 1, 0, -1};
constexpr int dy[4] = {-1, 0, 1, 0};
constexpr int dd[2] = {1, 3}; // turn right, left

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));
}

bool reach1[16][64][4]; // only go to kitchen
bool reach[16][64][4][16][64][4];

int main() {
    int w, h;
    while(cin >> w >> h, w) {
        memset(reach1, false, sizeof(reach1));
        memset(reach, false, sizeof(reach));
        vector<string> v(h);
        for(auto& s : v) cin >> s;

        auto can_move_to = [&] (int y, int x) {
            return 0 <= y && y < h && 0 <= x && x < w && v[y][x] != '#';
        };
        auto from = table(h, w, 4, vector<pii>{});
        auto to = table(h, w, 4, make_pair(-1, -1));
        int sy = -1, sx = -1, sd = -1, gy = -1, gx = -1, gd = -1;
        for(int i = 0; i < h; ++i) {
            for(int j = 0; j < w; ++j) {
                if(v[i][j] == '#') continue;
                for(int d = 0; d < 4; ++d) {
                    int y = i, x = j;
                    while(can_move_to(y + dy[d], x + dx[d])) {
                        y += dy[d];
                        x += dx[d];
                    }
                    from[y][x][d].emplace_back(i, j);
                    to[i][j][d] = make_pair(y, x);
                }

                if(v[i][j] == 'K') {
                    sy = i, sx = j;
                    for(int d = 0; d < 4; ++d) {
                        if(!can_move_to(sy + dy[d], sx + dx[d])) continue;
                        sd = d;
                    }
                }
                if(v[i][j] == 'M') {
                    gy = i, gx = j;
                    for(int d = 0; d < 4; ++d) {
                        if(!can_move_to(gy + dy[d], gx + dx[d])) continue;
                        gd = d;
                    }
                }
            }
        }

        function<bool(int, int, int)> go_to_kitchen = [&] (int y, int x, int d) {
            if(reach1[y][x][d]) return false;
            reach1[y][x][d] = true;
            if(y == gy && x == gx) return true;
            bool res = false;
            if(v[y + dy[d]][x + dx[d]] != '#') {
                res = go_to_kitchen(y + dy[d], x + dx[d], d);
            } else {
                res = go_to_kitchen(y, x, (d + 1) % 4);
                res |= go_to_kitchen(y, x, (d + 3) % 4);
            }
            return res;
        };

        queue<tuple<int, int, int, int, int, int>> que;
        for(int d = 0; d < 4; ++d) {
            reach[sy][sx][sd][sy][sx][d] = true;
            que.emplace(sy, sx, sd, sy, sx, d);
        }
        while(!que.empty()) {
            int y1, x1, d1, y2, x2, d2;
            tie(y1, x1, d1, y2, x2, d2) = que.front();
            que.pop();
            const int ny1 = to[y1][x1][d1].first, nx1 = to[y1][x1][d1].second;
            for(auto const& p : from[y2][x2][d2]) {
                const int ny2 = p.first, nx2 = p.second;
                if(v[ny2 + dy[(d2 + 2) % 4]][nx2 + dx[(d2 + 2) % 4]] == '#') {
                    reach[ny1][nx1][d1][ny2][nx2][d2] = true; // terminate
                }
                for(int i = 0; i < 2; ++i) {
                    const int nd1 = (d1 + dd[i]) % 4, nd2 = (d2 + dd[i]) % 4;
                    if(reach[ny1][nx1][nd1][ny2][nx2][nd2]) continue;
                    if(v[ny2 + dy[nd2]][nx2 + dx[nd2]] != '#') continue; // cannot turn at this point
                    reach[ny1][nx1][nd1][ny2][nx2][nd2] = true;
                    que.emplace(ny1, nx1, nd1, ny2, nx2, nd2);
                }
            }
        }

        bool f2 = false;
        for(int d1 = 0; d1 < 4; ++d1) {
            f2 |= reach[gy][gx][d1][gy][gx][gd];
        }

        if(f2) {
            cout << "He can accomplish his mission." << endl;
        } else if(go_to_kitchen(sy, sx, sd)) {
            cout << "He cannot return to the kitchen." << endl;
        } else {
            cout << "He cannot bring tea to his master." << endl;
        }
    }
}
accuracy: 1
time_ms: 450
memory_kb: 19924
final_rank: 7

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

using pii = pair<int, int>;

// direction
// 0: N, 1: E, 2:S, 3:W
constexpr int dx[4] = {0, 1, 0, -1};
constexpr int dy[4] = {-1, 0, 1, 0};
constexpr int dd[2] = {1, 3}; // turn right, left

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));
}

bool reach[16][64][4][16][64][4];

int main() {
    int w, h;
    while(cin >> w >> h, w) {
        memset(reach, false, sizeof(reach));
        vector<string> v(h);
        for(auto& s : v) cin >> s;

        auto can_move_to = [&] (int y, int x) {
            return 0 <= y && y < h && 0 <= x && x < w && v[y][x] != '#';
        };
        auto from = table(h, w, 4, vector<pii>{});
        auto to = table(h, w, 4, make_pair(-1, -1));
        int sy = -1, sx = -1, sd = -1, gy = -1, gx = -1, gd = -1;
        for(int i = 0; i < h; ++i) {
            for(int j = 0; j < w; ++j) {
                if(v[i][j] == '#') continue;
                for(int d = 0; d < 4; ++d) {
                    int y = i, x = j;
                    while(can_move_to(y + dy[d], x + dx[d])) {
                        y += dy[d];
                        x += dx[d];
                    }
                    from[y][x][d].emplace_back(i, j);
                    to[i][j][d] = make_pair(y, x);
                }

                if(v[i][j] == 'K') {
                    sy = i, sx = j;
                    for(int d = 0; d < 4; ++d) {
                        if(!can_move_to(sy + dy[d], sx + dx[d])) continue;
                        sd = d;
                    }
                }
                if(v[i][j] == 'M') {
                    gy = i, gx = j;
                    for(int d = 0; d < 4; ++d) {
                        if(!can_move_to(gy + dy[d], gx + dx[d])) continue;
                        gd = d;
                    }
                }
            }
        }

        bool f1 = false;
        { // only go to master
            auto reach = table(h, w, 4, false);
            queue<tuple<int, int, int>> que;
            que.emplace(sy, sx, sd);
            reach[sy][sx][sd] = true;
            while(!que.empty()) {
                int y, x, d; tie(y, x, d) = que.front();
                que.pop();
                const int ny = to[y][x][d].first, nx = to[y][x][d].second;
                for(int i = 0; i < 2; ++i) {
                    const int nd = (d + dd[i]) % 4;
                    if(reach[ny][nx][nd]) continue;
                    reach[ny][nx][nd] = true;
                    que.emplace(ny, nx, nd);
                }
            }
            for(int i = 0; i < 4; ++i) {
                f1 |= reach[gy][gx][i];
            }
        }
        queue<tuple<int, int, int, int, int, int>> que;
        for(int d = 0; d < 4; ++d) {
            reach[sy][sx][sd][sy][sx][d] = true;
            que.emplace(sy, sx, sd, sy, sx, d);
        }
        while(!que.empty()) {
            int y1, x1, d1, y2, x2, d2;
            tie(y1, x1, d1, y2, x2, d2) = que.front();
            que.pop();
            const int ny1 = to[y1][x1][d1].first, nx1 = to[y1][x1][d1].second;
            for(auto const& p : from[y2][x2][d2]) {
                const int ny2 = p.first, nx2 = p.second;
                if(v[ny2 + dy[(d2 + 2) % 4]][nx2 + dx[(d2 + 2) % 4]] == '#') {
                    reach[ny1][nx1][d1][ny2][nx2][d2] = true; // terminate
                }
                for(int i = 0; i < 2; ++i) {
                    const int nd1 = (d1 + dd[i]) % 4, nd2 = (d2 + dd[i]) % 4;
                    if(reach[ny1][nx1][nd1][ny2][nx2][nd2]) continue;
                    if(v[ny2 + dy[nd2]][nx2 + dx[nd2]] != '#') continue; // cannot turn at this point
                    reach[ny1][nx1][nd1][ny2][nx2][nd2] = true;
                    que.emplace(ny1, nx1, nd1, ny2, nx2, nd2);
                }
            }
        }

        bool f2 = false;
        for(int d1 = 0; d1 < 4; ++d1) {
            f2 |= reach[gy][gx][d1][gy][gx][gd];
        }

        if(f2) {
            cout << "He can accomplish his mission." << endl;
        } else if(f1) {
            cout << "He cannot return to the kitchen." << endl;
        } else {
            cout << "He cannot bring tea to his master." << endl;
        }
    }
}
accuracy: 1
time_ms: 450
memory_kb: 19880
final_rank: 6

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

using pii = pair<int, int>;

// direction
// 0: N, 1: E, 2:S, 3:W
constexpr int dx[4] = {0, 1, 0, -1};
constexpr int dy[4] = {-1, 0, 1, 0};
constexpr int dd[2] = {1, 3}; // turn right, left

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));
}

bool reach[16][64][4][16][64][4];

int main() {
    int w, h;
    while(cin >> w >> h, w) {
        fill((bool*)reach, (bool*)reach + 64 * 64 * 64 * 64, false);
        vector<string> v(h);
        for(auto& s : v) cin >> s;

        auto can_move_to = [&] (int y, int x) {
            return 0 <= y && y < h && 0 <= x && x < w && v[y][x] != '#';
        };
        auto from = table(h, w, 4, vector<pii>{});
        auto to = table(h, w, 4, make_pair(-1, -1));
        for(int i = 0; i < h; ++i) {
            for(int j = 0; j < w; ++j) {
                if(v[i][j] == '#') continue;
                for(int d = 0; d < 4; ++d) {
                    int y = i, x = j;
                    while(can_move_to(y + dy[d], x + dx[d])) {
                        y += dy[d];
                        x += dx[d];
                    }
                    from[y][x][d].emplace_back(i, j);
                    to[i][j][d] = make_pair(y, x);
                }
            }
        }

        int sy = -1, sx = -1, sd = -1, gy = -1, gx = -1, gd = -1;
        for(int i = 0; i < h; ++i) {
            for(int j = 0; j < w; ++j) {
                if(v[i][j] == 'K') {
                    sy = i, sx = j;
                    for(int d = 0; d < 4; ++d) {
                        if(can_move_to(sy + dy[d], sx + dx[d])) {
                            sd = d;
                        }
                    }
                }
                if(v[i][j] == 'M') {
                    gy = i, gx = j;
                    for(int d = 0; d < 4; ++d) {
                        if(can_move_to(gy + dy[d], gx + dx[d])) {
                            gd = d;
                        }
                    }
                }
            }
        }

        bool f1 = false;
        { // only go to master
            auto reach = table(h, w, 4, false);
            queue<tuple<int, int, int>> que;
            que.emplace(sy, sx, sd);
            reach[sy][sx][sd] = true;
            while(!que.empty()) {
                int y, x, d; tie(y, x, d) = que.front();
                que.pop();
                const int ny = to[y][x][d].first, nx = to[y][x][d].second;
                for(int i = 0; i < 2; ++i) {
                    const int nd = (d + dd[i]) % 4;
                    if(reach[ny][nx][nd]) continue;
                    reach[ny][nx][nd] = true;
                    que.emplace(ny, nx, nd);
                }
            }
            for(int i = 0; i < 4; ++i) {
                f1 |= reach[gy][gx][i];
            }
        }
        queue<tuple<int, int, int, int, int, int>> que;
        for(int d = 0; d < 4; ++d) {
            reach[sy][sx][sd][sy][sx][d] = true;
            que.emplace(sy, sx, sd, sy, sx, d);
        }
        while(!que.empty()) {
            int y1, x1, d1, y2, x2, d2;
            tie(y1, x1, d1, y2, x2, d2) = que.front();
            que.pop();
            const int ny1 = to[y1][x1][d1].first, nx1 = to[y1][x1][d1].second;
            for(auto const& p : from[y2][x2][d2]) {
                const int ny2 = p.first, nx2 = p.second;
                if(v[ny2 + dy[(d2 + 2) % 4]][nx2 + dx[(d2 + 2) % 4]] == '#') {
                    reach[ny1][nx1][d1][ny2][nx2][d2] = true; // terminate
                }
                for(int i = 0; i < 2; ++i) {
                    const int nd1 = (d1 + dd[i]) % 4, nd2 = (d2 + dd[i]) % 4;
                    if(reach[ny1][nx1][nd1][ny2][nx2][nd2]) continue;
                    if(v[ny2 + dy[nd2]][nx2 + dx[nd2]] != '#') continue; // cannot turn at this point
                    reach[ny1][nx1][nd1][ny2][nx2][nd2] = true;
                    que.emplace(ny1, nx1, nd1, ny2, nx2, nd2);
                }
            }
        }

        bool f2 = false;
        for(int d1 = 0; d1 < 4; ++d1) {
            f2 |= reach[gy][gx][d1][gy][gx][gd];
        }

        if(f2) {
            cout << "He can accomplish his mission." << endl;
        } else if(f1) {
            cout << "He cannot return to the kitchen." << endl;
        } else {
            cout << "He cannot bring tea to his master." << endl;
        }
    }
}
accuracy: 1
time_ms: 930
memory_kb: 19976
final_rank: 9