Problem:
迷子の双子
たかゆき君とかずゆき君は仲良しの双子ですが、行動が真逆です。 例えば、たかゆき君が西に行けば、かずゆき君は東へ行き、かずゆき君が北へ行けば、たかゆき君は南へ行きます。 現在 2 人はデパートに来ており、別々の場所にいます。真逆に移動してしまう 2 人ができるだけ早く出会うためにはどうしたらよいでしょうか?
デパートは横
W
個 × 縦
H
個のマスで構成されるグリッドで表され、2 人は単位時間に東西南北に 1 マス分移動することができます。ただし、グリッドの範囲外や障害物のあるマスに移動することはできません。
図のように、グリッドのマスの位置は座標 (
x
,
y
) で表されます。
グリッドの情報と 2 人の初期位置を入力とし、2 人が出会うまでの最短の時間を出力するプログラムを作成してください。出会うことができない場合や、出会うのに 100 以上の時間を要する場合は、NA と出力してください。グリッドの情報は、
H
行
W
列の数字、2 人の位置情報は座標によって与えられます。
移動後にたかゆき君かかずゆき君のうち、どちらか一方が障害物やグリッドの範囲外に位置してしまうときには、移動ができないので、障害物やグリッドの範囲外に位置する方は元の場所に戻りますが、そうでない方は元の場所に戻ることなく動くことができます。
なお、2 人が出会うとは、移動後に 2 人が同じマスに止まることを言います。2 人がすれ違っても、出会ったことにはなりません。
Input
複数のデータセットの並びが入力として与えられます。入力の終わりはゼロふたつの行で示されます。
各データセットは以下の形式で与えられます。
W
H
tx
ty
kx
ky
d
11
d
21
...
d
W1
d
12
d
22
...
d
W2
:
d
1H
d
2H
...
d
WH
1 行目にデパートの大きさ
W
,
H
(1 ≤
W, H
≤ 50) が与えられます。2 行目にたかゆき君の初期位置
tx, ty
、3 行目にかずゆき君の初期位置
kx, ky
が与えられます。
続く
H
行にデパートの情報が与えられます。
d
i,j
はマス (
i, j
) の種類を表し、0 のとき移動可能なマス、1 のとき障害物があるマスを表します。
データセットの数は 100 を超えません。
Output
入力データセットごとに、最短の時間を１行に出力します。
Sample Input
6 6
2 4
6 2
0 0 0 0 1 0
0 1 0 0 0 0
0 1 0 0 0 0
0 0 0 1 0 0
0 0 0 0 0 1
0 0 0 0 0 0
3 3
1 1
3 3
0 0 0
0 1 0
0 0 0
0 0
Output for the Sample Input
3
NA

Submitted solutions:

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

using vi = vector<int>;
using vvi = vector<vi>;

constexpr int INF = 1e9;

int main() {
    using state = tuple<int, int, int, int, int>;

    int W, H;
    while(cin >> W >> H, W) {
        int tx, ty, kx, ky;
        cin >> tx >> ty >> kx >> ky;
        tx--; ty--; kx--; ky--;
        vector<vector<int>> v(H, vector<int>(W));
        for(int i=0; i<H; ++i) {
            for(int j=0; j<W; ++j) {
                cin >> v[i][j];
            }
        }
        vector<vector<vvi>> d(H, vector<vvi>(W, vvi(H, vi(W, INF))));
        d[ty][tx][ky][kx] = 0;
        queue<state> que;
        que.push(make_tuple(0, ty, tx, ky, kx));
        int dx[4] = {0, -1, 0, 1},
            dy[4] = {1, 0, -1, 0};
        auto check = [&v, W, H](int y, int x) {
            return 0 <= y && y < H && 0 <= x && x < W && v[y][x] == 0;
        };
        while(!que.empty()) {
            int cd, y1, x1, y2, x2;
            tie(cd, y1, x1, y2, x2) = que.front();
            que.pop();
            for(int i=0; i<4; ++i) {
                int ny1 = y1+dy[i], nx1 = x1+dx[i];
                if(!check(ny1, nx1)) {
                    ny1 = y1;
                    nx1 = x1;
                }
                int ny2 = y2-dy[i], nx2 = x2-dx[i];
                if(!check(ny2, nx2)) {
                    ny2 = y2;
                    nx2 = x2;
                }
                if(d[ny1][nx1][ny2][nx2] > cd + 1 && cd + 1 < 100) {
                    d[ny1][nx1][ny2][nx2] = cd + 1;
                    que.push(make_tuple(cd+1, ny1, nx1, ny2, nx2));
                }
            }
        }
        int res = INF;
        for(int i=0; i<H; ++i) {
            for(int j=0; j<W; ++j) {
                res = min(res, d[i][j][i][j]);
            }
        }
        if(res == INF) {
            cout << "NA" << endl;
        } else {
            cout << res << endl;
        }
    }
}
accuracy: 1
time_ms: 1880
memory_kb: 32860
final_rank: 8

code_snippet: #include <bits/stdc++.h>
using namespace std;
// #include<atcoder/all>
// using mint = atcoder::modint998244353;
using ld = long double;
#define fi first
#define se second
#define all(x) x.begin(),x.end()
#define rep(i,n) for(int i=0;i<(int)(n);++i)
template<typename T>bool chmin(T&a,T b){return b<a?(a=b,1):0;}
template<typename T>bool chmax(T&a,T b){return b>a?(a=b,1):0;}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    
    for(int W,H;cin>>W>>H,W!=0;){
        int tx,ty,kx,ky;
        cin>>tx>>ty>>kx>>ky;
        ty--;tx--;ky--;kx--;

        vector A(H,vector<int>(W,0));
        rep(i,H)rep(j,W)cin>>A[i][j];

        vector dp(H,vector<vector<vector<int>>>(W,vector<vector<int>>(H,vector<int>(W,1e9))));
        dp[ty][tx][ky][kx]=0;
        queue<array<int,4>> q;
        q.push({ty,tx,ky,kx});
        while(!q.empty()){
            auto [y1,x1,y2,x2]=q.front();
            q.pop();
            vector<int> dd={0,1,0,-1,0};
            rep(i,4){
                int ny1=y1+dd[i];
                int nx1=x1+dd[i+1];
                int ny2=y2+dd[(i+2)%4];
                int nx2=x2+dd[(i+3)%4];

                if(ny1<0||H<=ny1||nx1<0||W<=nx1||A[ny1][nx1]) ny1=y1,nx1=x1;
                if(ny2<0||H<=ny2||nx2<0||W<=nx2||A[ny2][nx2]) ny2=y2,nx2=x2;
                if(dp[ny1][nx1][ny2][nx2]!=1e9) continue;
                dp[ny1][nx1][ny2][nx2]=dp[y1][x1][y2][x2]+1;
                q.push({ny1,nx1,ny2,nx2});
            }
        }
        int ans=1e9;
        rep(i,H)rep(j,W) chmin(ans, dp[i][j][i][j]); 
        if(ans>=100) cout<<"NA\n";
        else cout<<ans<<"\n";
    }
}
accuracy: 1
time_ms: 2710
memory_kb: 32964
final_rank: 16

code_snippet: #pragma region Macros
 
#pragma GCC optimize("O3,unroll-loops")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,fma,abm,mmx,avx,avx2,popcnt")
 
#include <bits/extc++.h>
// #include <atcoder/all>
// using namespace atcoder;
using namespace std;
using namespace __gnu_pbds;
 
// #include <boost/multiprecision/cpp_dec_float.hpp>
// #include <boost/multiprecision/cpp_int.hpp>
// namespace mp = boost::multiprecision;
// using Bint = mp::cpp_int;
// using Bdouble = mp::number<mp::cpp_dec_float<256>>;
// Bdouble Beps = 0.00000000000000000000000000000001; // 1e-32
// const bool equals(Bdouble a, Bdouble b) { return mp::fabs(a - b) < Beps; }

#define pb emplace_back
// #define int ll
#define endl '\n'
 
#define sqrt __builtin_sqrtl
#define cbrt __builtin_cbrtl
#define hypot __builtin_hypotl
 
// #define next asdnext
// #define prev asdprev
 
using ll = long long;
using ld = long double;
const ld PI = acosl(-1);
const int INF = 1 << 30;
const ll INFL = 1LL << 61;
const int MOD = 998244353;
// const int MOD = 1000000007;

const ld EPS = 1e-10;
const bool equals(ld a, ld b) { return fabs((a) - (b)) < EPS; }
 
const vector<int> dx = {0, 1, 0, -1, 1, 1, -1, -1}; // → ↓ ← ↑ ↘ ↙ ↖ ↗
const vector<int> dy = {1, 0, -1, 0, 1, -1, -1, 1};
 
#define EC int
struct Edge {
    int from, to;
    EC cost;
    Edge() : from(-1), to(-1), cost(-1) {}
    Edge(int to, EC cost) : to(to), cost(cost) {}
    Edge(int from, int to, EC cost) : from(from), to(to), cost(cost) {}
    bool operator ==(const Edge& e) {
        return this->from == e.from && this->to == e.to && this->cost == e.cost;
    }
    bool operator !=(const Edge& e) {
        return this->from != e.from or this->to != e.to or this->cost != e.cost;
    }
    bool operator <(const Edge& e) { return this->cost < e.cost; }
    bool operator >(const Edge& e) { return this->cost > e.cost; }
};
 
chrono::system_clock::time_point start;
__attribute__((constructor))
void constructor() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout << fixed << setprecision(10);
    start = chrono::system_clock::now();
}
 
random_device seed_gen;
mt19937_64 rng(seed_gen());
uniform_int_distribution<int> dist_x(0, 1e9);
struct RNG {
    unsigned Int() {
        return dist_x(rng);
    }
    unsigned Int(unsigned l, unsigned r) {
        return dist_x(rng) % (r - l + 1) + l;
    }
    ld Double() {
        return ld(dist_x(rng)) / 1e9;
    }
} rnd;

namespace bit_function {
    using i64 = ll;
    // using i64 = uint64_t;
    // bit演算, x==0の場合は例外処理した方がよさそう. 区間は [l, r)
    i64 lrmask(int l, int r) { return (1LL << r) - (1LL << l); }
    i64 sub_bit(i64 x, int l, int r) { i64 b = x & ((1LL << r) - (1LL << l)); return b >> l; } // r溢れ可
    i64 bit_width(i64 x) { return 64 - __builtin_clzll(x) + (x == 0); }
    
    i64 popcount(i64 x) { return __builtin_popcountll(x); }
    i64 popcount(i64 x, int l, int r) { return __builtin_popcountll(sub_bit(x, l, r)); }
    i64 unpopcount(i64 x) { return bit_width(x) - __builtin_popcountll(x); } // 最上位bitより下のみ
    i64 unpopcount(i64 x, int l, int r) { return r - l - __builtin_popcountll(sub_bit(x, l, r)); } // 最上位bitより上も含まれうる
    bool is_pow2(i64 x) { return __builtin_popcountll(x) == 1; } // xが負のときは常にfalse
    bool is_pow4(i64 x) { return __builtin_popcountll(x) == 1 && __builtin_ctz(x) % 2 == 0; }
    //bool is_pow4(ll x) { return __builtin_popcountll(x) == 1 && (x&0x55555555); }
    
    int top_bit(i64 x) { return 63 - __builtin_clzll(x);} // 2^kの位 (x > 0)
    int bot_bit(i64 x) { return __builtin_ctzll(x);} // 2^kの位 (x > 0)
    int next_bit(i64 x, int k) { // upper_bound
        x >>= (k + 1);
        int pos = k + 1;
        while (x > 0) {
            if (x & 1) return pos;
            x >>= 1;
            pos++;
        }
        return -1;
    }
    int prev_bit(i64 x, int k) {
        // k = min(k, bit_width(x)); ?
        int pos = 0;
        while (x > 0 && pos < k) {
            if (x & 1) {
                if (pos < k) return pos;
            }
            x >>= 1;
            pos++;
        }
        return -1;
    }
    int kth_bit(i64 x, int k) { // kは1-indexed
        int pos = 0, cnt = 0;
        while (x > 0) {
            if (x & 1) {
                cnt++;
                if (cnt == k) return pos;
            }
            x >>= 1;
            pos++;
        }
        return -1;
    }
    i64 msb(i64 x) { if (x == 0) return 0; return 1LL << (63 - __builtin_clzll(x)); } // mask
    i64 lsb(i64 x) { return (x & -x); } // mask
    
    int countl_zero(i64 x) { return __builtin_clzll(x); }
    int countl_one(i64 x) { // countl_oneと定義が異なるので注意
        i64 ret = 0, k = 63 - __builtin_clzll(x);
        while (k != -1 && (x & (1LL << k))) { k--; ret++; }
        return ret;
    }
    int countr_zero(i64 x) { return __builtin_ctzll(x); } // x=0のとき64
    int countr_one(i64 x) { int ret = 0; while (x & 1) { x >>= 1; ret++; } return ret; }
    // int countr_one(ll x) { return __builtin_popcount(x ^ (x & -~x));

    i64 l_one(i64 x) { // 最上位で連なってる1のmask
        if (x == 0) return 0;
        i64 ret = 0, k = 63 - __builtin_clzll(x);
        while (k != -1 && (x & (1LL << k))) { ret += 1LL << k; k--; }
        return ret;
    }
    
    int floor_log2(i64 x) { return 63 - __builtin_clzll(x); } // top_bit
    int ceil_log2(i64 x) { return 64 - __builtin_clzll(x - 1); }
    i64 bit_floor(i64 x) { if (x == 0) return 0; return 1LL << (63 - __builtin_clzll(x)); } // msb
    i64 bit_ceil(i64 x) { if (x == 0) return 0; return 1LL << (64 - __builtin_clzll(x - 1)); }
    
    i64 rotl(i64 x, int k) { // 有効bit内でrotate. オーバーフロー注意
        i64 w = bit_width(x); k %= w;
        return ((x << k) | (x >> (w - k))) & ((1LL << w) - 1);
    }
    // i64 rotl(i64 x, i64 l, i64 m, i64 r) {}
    i64 rotr(i64 x, int k) {
        i64 w = bit_width(x); k %= w;
        return ((x >> k) | (x << (w - k))) & ((1LL << w) - 1);
    }
    // i64 rotr(i64 x, i64 l, i64 m, i64 r) {}
    i64 bit_reverse(i64 x) { // 有効bit内で左右反転
        i64 r = 0, w = bit_width(x);
        for (i64 i = 0; i < w; i++) r |= ((x >> i) & 1) << (w - i - 1);
        return r;
    }
    // i64 bit_reverse(i64 x, int l, int r) {}
    
    bool is_palindrome(i64 x) { return x == bit_reverse(x); }
    bool is_palindrome(i64 x, int l, int r) { i64 b = sub_bit(x, l, r); return b == bit_reverse(b); }
    i64 concat(i64 a, i64 b) { return (a << bit_width(b)) | b; } // オーバーフロー注意
    i64 erase(i64 x, int l, int r) { return x >> r << l | x & ((1LL << l) - 1); } // [l, r) をカット
    
    i64 hamming(i64 a, i64 b) { return __builtin_popcountll(a ^ b); }
    i64 hamming(i64 a, i64 b, int l, int r) { return __builtin_popcountll(sub_bit(a, l, r) ^ sub_bit(b, l, r)); }
    i64 compcount(i64 x) { return (__builtin_popcountll(x ^ (x >> 1)) + (x & 1)) / 2; }
    i64 compcount2(i64 x) { return compcount(x & (x >> 1)); } // 長さ2以上の連結成分の個数
    i64 adjacount(i64 x) { return __builtin_popcountll(x & (x >> 1)); } // 隣接する1のペアの個数
    
    i64 next_combination(i64 x) {
        i64 t = x | (x - 1); return (t + 1) | (((~t & -~t) - 1) >> (__builtin_ctzll(x) + 1));
    }
} using namespace bit_function;

namespace util_function {
    namespace Std = std;
    __int128_t POW(__int128_t x, int n) {
        __int128_t ret = 1;
        assert(n >= 0);
        if (x == 1 or n == 0) ret = 1;
        else if (x == -1 && n % 2 == 0) ret = 1; 
        else if (x == -1) ret = -1; 
        else if (n % 2 == 0) {
            // assert(x < INFL);
            ret = POW(x * x, n / 2);
        } else {
            // assert(x < INFL);
            ret = x * POW(x, n - 1);
        }
        return ret;
    }
    int per(int x, int y) { // x = qy + r (0 <= r < y) を満たすq
        assert(y != 0);
        if (x >= 0 && y > 0) return x / y;
        if (x >= 0 && y < 0) return x / y - (x % y < 0);
        if (x < 0 && y < 0) return x / y + (x % y < 0);
        return x / y - (x % y < 0); //  (x < 0 && y > 0) 
    }
    int mod(int x, int y) { // x = qy + r (0 <= r < y) を満たすr
        assert(y != 0);
        return x - y * per(x, y);
    } // https://yukicoder.me/problems/no/2781
    int floor(int x, int y) { // (ld)x / y 以下の最大の整数
        assert(y != 0);
        if (y < 0) x = -x, y = -y;
        return x >= 0 ? x / y : (x + 1) / y - 1;
    }
    int ceil(int x, int y) { // (ld)x / y 以上の最小の整数
        assert(y != 0);
        if (y < 0) x = -x, y = -y;
        return x > 0 ? (x - 1) / y + 1 : x / y;
    }
    int round(int x, int y) { // (ld)(x/y)を小数点第1位について四捨五入
        assert(y != 0);
        return (x * 2 + y) / (y * 2);
    }
    int round(int x, int y, int k) { // (ld)(x/y)を10^kの位に関して四捨五入
        assert(y != 0 && k >= 0);
        if (k == 0) return (x * 2 + y) / (y * 2);
        x /= y * POW(10, k - 1);
        if (x % 10 >= 5) return (x + 10 - x % 10) * POW(10, k - 1);
        return x * POW(10, k - 1);
    }
    int round2(int x, int y) { // 五捨五超入 // 未verify
        assert(y != 0);
        if (y < 0) y = -y, x = -x;
        int z = x / y;
        if ((z * 2 + 1) * y <= y * 2) z++;
        return z;
    }
    ld round(ld x, int k) { // xを10^kの位に関して四捨五入. to_string(x, k)優先
        // x += EPS;
        ld d = pow(10, -k);
        return Std::round(x * d) / d;
    }
    ld floor(ld x, int k) { // xを10^kの位に関してflooring
        // x += EPS;
        ld d = pow(10, -k);
        return Std::floor(x * d) / d; // 未verify
    }
    ld ceil(ld x, int k) { // xを10^kの位に関してceiling
        // x -= EPS;
        ld d = pow(10, -k);
        return Std::ceil(x * d) / d; // 未verify
    }
    // int kth(int x, int y, int k) { // x / yの10^kの位の桁
    // }
    int floor(ld x, ld y) { // 誤差対策TODO
        assert(!equals(y, 0));
        return Std::floor(x / y);
        // floor(x) = ceil(x - 1) という話も
    }
    int ceil(ld x, ld y) { // 誤差対策TODO // ceil(p/q) = -floor(-(p/q))らしい
        assert(!equals(y, 0));
        return Std::ceil(x / y);
        // ceil(x) = floor(x + 1)
    }
    int perl(ld x, ld y) { // x = qy + r (0 <= r < y, qは整数) を満たす q
        // 未verify. 誤差対策TODO. EPS外してもいいかも。
        assert(!equals(y, 0));
        if (x >= 0 && y > 0) return Std::floor(x / y)+EPS;
        if (x >= 0 && y < 0) return -Std::floor(x / fabs(y));
        if (x < 0 && y < 0) return Std::floor(x / y) + (x - Std::floor(x/y)*y < -EPS);
        return Std::floor(x / y) - (x - Std::floor(x/y)*y < -EPS); //  (x < 0 && y > 0) 
    }
    ld modl(ld x, ld y) { // x = qy + r (0 <= r < y, qは整数) を満たす r
        // 未verify. 誤差対策TODO. -0.0が返りうる。
        assert(!equals(y, 0));
        if (x >= 0) return x - fabs(y)*fabs(per(x, y));
        return x - fabs(y)*floor(x, fabs(y));
    }
    int seisuu(ld x) { return (int)x; } // 整数部分. 誤差対策TODO
    int modf(ld x) {
        if (x < 0) return ceill(x);
        else return floorl(x);
    }
    // 正なら+EPS, 負なら-EPSしてから、文字列に直して小数点以下を捨てる?
    int seisuu(int x, int y) {
        assert(y != 0);
        return x / y;
    }
    int seisuu(ld x, ld y) { // 誤差対策TODO
        assert(!equals(y, 0));
        return (int)(x / y);
    }

    int floor_log(int base, int x) {
        assert(base >= 2);
        int ret = 0, now = 1;
        while (now <= x) {
            now *= base;
            if (now <= x) ret++;
        }
        return ret;
    }
    int ceil_log(int base, int x) {
        assert(base >= 2);
        int ret = 0, now = 1;
        while (now < x) {
            now *= base;
            ret++;
        }
        return ret;
    }

    template <class T> pair<T, T> max(const pair<T, T> &a, const pair<T, T> &b) {
        if (a.first > b.first or a.first == b.first && a.second > b.second) return a;
        return b;
    }
    template <class T> pair<T, T> min(const pair<T, T> &a, const pair<T, T> &b) {
        if (a.first < b.first or a.first == b.first && a.second < b.second) return a;
        return b;
    }
    
    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 (a > b) { a = b; return true; } return false;
    }
    template <class T> T mid(T a, T b, T c) { // 誤差対策TODO
        return a + b + c - Std::max({a, b, c}) - Std::min({a, b, c});
    }
    template <class T> void Sort(T &a, T &b, bool rev = false) { 
        if (rev == false) if (a > b) swap(a, b);
        else if (b > a) swap(b, a);
    }
    template <typename T, typename... Args>
    void Sort(T& a, T& b, T& c, Args&... args) {
        vector<T> vec = {a, b, c, args...};
        sort(vec.begin(), vec.end());
        auto it = vec.begin();
        a = *it++; b = *it++; c = *it++;
        int dummy[] = { (args = *it++, 0)... };
        static_cast<void>(dummy);
    }
    template <typename T, typename... Args>
    void Sortr(T& a, T& b, T& c, Args&... args) {
        vector<T> vec = {a, b, c, args...};
        sort(vec.rbegin(), vec.rend());
        auto it = vec.begin();
        a = *it++; b = *it++; c = *it++;
        int dummy[] = { (args = *it++, 0)... };
        static_cast<void>(dummy);
    }

    istream &operator >>(istream &is, __int128_t& x) {
        string S; is >> S;
        __int128_t ret = 0;
        int f = 1;
        if (S[0] == '-') f = -1; 
        for (int i = 0; i < S.length(); i++)
            if ('0' <= S[i] && S[i] <= '9')
                ret = ret * 10 + S[i] - '0';
        x = ret * f;
        return (is);
    }
    ostream &operator <<(ostream &os, __int128_t x) {
        ostream::sentry s(os);
        if (s) {
            __uint128_t tmp = x < 0 ? -x : x;
            char buffer[128]; char *d = end(buffer);
            do {
                --d; *d = "0123456789"[tmp % 10]; tmp /= 10;
            } while (tmp != 0);
            if (x < 0) { --d; *d = '-'; }
            int len = end(buffer) - d;
            if (os.rdbuf()->sputn(d, len) != len) os.setstate(ios_base::badbit);
        }
        return os;
    }
    
    __int128_t stoll(string &S) {
        __int128_t ret = 0; int f = 1;
        if (S[0] == '-') f = -1; 
        for (int i = 0; i < S.length(); i++)
            if ('0' <= S[i] && S[i] <= '9') ret = ret * 10 + S[i] - '0';
        return ret * f;
    }
    __int128_t gcd(__int128_t a, __int128_t b) { return b ? gcd(b, a % b) : a; }
    __int128_t lcm(__int128_t a, __int128_t b) {
        return a / gcd(a, b) * b;
        // lcmが__int128_tに収まる必要あり
    }
    
    string to_string(ld x, int k) { // xの小数第k位までをstring化する
        assert(k >= 0);
        stringstream ss;
        ss << setprecision(k + 2) << x;
        string s = ss.str();
        if (s.find('.') == string::npos) s += '.';
        int pos = s.find('.');
        for (int i = 0; k >= (int)s.size() - 1 - pos; i++) s += '0';
        s.pop_back();
        if (s.back() == '.') s.pop_back();
        return s;
    
        // stringstream ss; // 第k+1位を四捨五入して第k位まで返す
        // ss << setprecision(k + 1) << x;
        // string s = ss.str();
        // if (s.find('.') == string::npos) s += '.';
        // int pos = s.find('.');
        // for (int i = 0; k > (int)s.size() - 1 - pos; i++) s += '0';
        // if (s.back() == '.') s.pop_back();
        // return s;
    }
    string to_string(__int128_t x) {
        string ret = "";
        if (x < 0) { ret += "-"; x *= -1; }
        while (x) { ret += (char)('0' + x % 10); x /= 10; }
        reverse(ret.begin(), ret.end());
        return ret;
    }
    string to_string(char c) { string s = ""; s += c; return s; }
} using namespace util_function;

struct custom_hash {
    static uint64_t splitmix64(uint64_t x) {
        x += 0x9e3779b97f4a7c15;
        x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
        x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
        return x ^ (x >> 31);
    }
 
    size_t operator()(uint64_t x) const {
        static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
        return splitmix64(x + FIXED_RANDOM);
    }
};

template<class T> size_t HashCombine(const size_t seed,const T &v) {
    return seed^(hash<T>()(v)+0x9e3779b9+(seed<<6)+(seed>>2));
}
template<class T,class S> struct hash<pair<T,S>>{
    size_t operator()(const pair<T,S> &keyval) const noexcept {
        return HashCombine(hash<T>()(keyval.first), keyval.second);
    }
};
template<class T> struct hash<vector<T>>{
    size_t operator()(const vector<T> &keyval) const noexcept {
        size_t s=0;
        for (auto&& v: keyval) s=HashCombine(s,v);
        return s;
    }
};
template<int N> struct HashTupleCore{
    template<class Tuple> size_t operator()(const Tuple &keyval) const noexcept{
        size_t s=HashTupleCore<N-1>()(keyval);
        return HashCombine(s,get<N-1>(keyval));
    }
};
template <> struct HashTupleCore<0>{
    template<class Tuple> size_t operator()(const Tuple &keyval) const noexcept{ return 0; }
};
template<class... Args> struct hash<tuple<Args...>>{
    size_t operator()(const tuple<Args...> &keyval) const noexcept {
        return HashTupleCore<tuple_size<tuple<Args...>>::value>()(keyval);
    }
};

template<typename T>
class Compress { // 試験運用, バグったらTをintにする
public:
    int sz = 0;
    // gp_hash_table<T, int, custom_hash> Z;
    // gp_hash_table<int, T, custom_hash> UZ;
    unordered_map<T, int> Z;    // 元の値 -> 圧縮した値
    unordered_map<int, T> UZ;   // 圧縮した値 -> 元の値
 
    Compress() {}
    Compress(const vector<T> &V, T base = 0) {
        this->sz = base;
        set<T> s(V.begin(), V.end());
 
        for (T x : s) {
            this->Z[x] = this->sz;
            this->UZ[this->sz] = x;
            this->sz++;
        }
    }
    
    Compress(const vector<T> &V1, const vector<T> &V2, T base = 0) {
        this->sz = base;
        vector<T> V3 = V2;
        V3.insert(V3.end(), V1.begin(), V1.end());
        set<T> s(V3.begin(), V3.end());
 
        for (T x : s) {
            this->Z[x] = this->sz;
            this->UZ[this->sz] = x;
            this->sz++;
        }
    }
 
    Compress(const vector<T> &V1, const vector<T> &V2, const vector<T> &V3, T base = 0) {
        this->sz = base;
        vector<T> V4 = V1;
        V4.insert(V4.end(), V2.begin(), V2.end());
        V4.insert(V4.end(), V3.begin(), V3.end());
        set<T> s(V4.begin(), V4.end());
 
        for (T x : s) {
            this->Z[x] = this->sz;
            this->UZ[this->sz] = x;
            this->sz++;
        }
    }
 
    Compress(const vector<T> &V1, const vector<T> &V2,
            const vector<T> &V3, const vector<T> &V4, T base = 0) {
        this->sz = base;
        vector<T> V5 = V1;
        V5.insert(V5.end(), V2.begin(), V2.end());
        V5.insert(V5.end(), V3.begin(), V3.end());
        V5.insert(V5.end(), V4.begin(), V4.end());
        set<T> s(V5.begin(), V5.end());
 
        for (T x : s) {
            this->Z[x] = this->sz;
            this->UZ[this->sz] = x;
            this->sz++;
        }
    }
 
    vector<int> zip(const vector<T> &V) {
        vector<int> ret(V.size());
        for (int i = 0; i < (int)V.size(); i++) {
            ret[i] = Z[V[i]];
        }
        return ret;
    }
 
    vector<T> unzip(const vector<int> &V) {
        vector<T> ret(V.size());
        for (int i = 0; i < (int)V.size(); i++) {
            ret[i] = UZ[V[i]];
        }
        return ret;
    }
 
    int size() { return sz; }
 
    T encode(int x) { return Z[x]; }
    int decode(T x) {
        if (UZ.find(x) == UZ.end()) return -1; // xが元の配列に存在しないとき
        return UZ[x];
    }
};
 
class UnionFind {
public:
	UnionFind() = default;
    UnionFind(int N) : par(N), sz(N, 1) {
        iota(par.begin(), par.end(), 0);
    }
	int root(int x) {
		if (par[x] == x) return x;
		return (par[x] = root(par[x]));
	}
	bool unite(int x, int y) {
		int rx = root(x);
		int ry = root(y);
        if (rx == ry) return false;
		if (sz[rx] < sz[ry]) swap(rx, ry);
		sz[rx] += sz[ry];
		par[ry] = rx;
        return true;
	}
	bool issame(int x, int y) { return (root(x) == root(y)); }
	int size(int x) { return sz[root(x)]; }
    vector<vector<int>> groups(int N) {
        vector<vector<int>> G(N);
        for (int x = 0; x < N; x++) {
            G[root(x)].push_back(x);
        }
		G.erase( remove_if(G.begin(), G.end(),
            [&](const vector<int>& V) { return V.empty(); }), G.end());
        return G;
    }
private:
	vector<int> par, sz;
};
 
template<typename T> struct BIT {
    int N;             // 要素数
    vector<T> bit[2];  // データの格納先
    BIT(int N_, int x = 0) {
        N = N_ + 1;
        bit[0].assign(N, 0); bit[1].assign(N, 0);
        if (x != 0) {
            for (int i = 0; i < N; i++) add(i, x);
        }
    }
    BIT(const vector<T> &A) {
        N = A.size() + 1;
        bit[0].assign(N, 0); bit[1].assign(N, 0);
        for (int i = 0; i < (int)A.size(); i++) add(i, A[i]);
    }
    void add_sub(int p, int i, T x) {
        while (i < N) { bit[p][i] += x; i += (i & -i); }
    }
    void add(int l, int r, T x) {
        add_sub(0, l + 1, -x * l); add_sub(0, r + 1, x * r);
        add_sub(1, l + 1, x); add_sub(1, r + 1, -x);
    }
    void add(int i, T x) { add(i, i + 1, x); }
    T sum_sub(int p, int i) {
        T ret = 0;
        while (i > 0) { ret += bit[p][i]; i -= (i & -i); }
        return ret;
    }
    T sum(int i) { return sum_sub(0, i) + sum_sub(1, i) * i; }
    T sum(int l, int r) { return sum(r) - sum(l); }
    T get(int i) { return sum(i, i + 1); }
    void set(int i, T x) { T s = get(i); add(i, -s + x); }
};
 
template<int mod> class Modint {
public:
    int val = 0;
    Modint(int x = 0) { while (x < 0) x += mod; val = x % mod; }
    Modint(const Modint &r) { val = r.val; }
 
    Modint operator -() { return Modint(-val); } // 単項
    Modint operator +(const Modint &r) { return Modint(*this) += r; }
    Modint operator +(const int &q) { Modint r(q); return Modint(*this) += r; }
    Modint operator -(const Modint &r) { return Modint(*this) -= r; }
    Modint operator -(const int &q) { Modint r(q); return Modint(*this) -= r; }
    Modint operator *(const Modint &r) { return Modint(*this) *= r; }
    Modint operator *(const int &q) { Modint r(q); return Modint(*this) *= r; }
    Modint operator /(const Modint &r) { return Modint(*this) /= r; }
    Modint operator /(const int &q) { Modint r(q); return Modint(*this) /= r; }
    
    Modint& operator ++() { val++; if (val >= mod) val -= mod; return *this; } // 前置
    Modint operator ++(signed) { ++*this; return *this; } // 後置
    Modint& operator --() { val--; if (val < 0) val += mod; return *this; }
    Modint operator --(signed) { --*this; return *this; }
    Modint &operator +=(const Modint &r) { val += r.val; if (val >= mod) val -= mod; return *this; }
    Modint &operator +=(const int &q) { Modint r(q); val += r.val; if (val >= mod) val -= mod; return *this; }
    Modint &operator -=(const Modint &r) { if (val < r.val) val += mod; val -= r.val; return *this; }
    Modint &operator -=(const int &q) { Modint r(q);  if (val < r.val) val += mod; val -= r.val; return *this; }
    Modint &operator *=(const Modint &r) { val = val * r.val % mod; return *this; }
    Modint &operator *=(const int &q) { Modint r(q); val = val * r.val % mod; return *this; }
    Modint &operator /=(const Modint &r) {
        int a = r.val, b = mod, u = 1, v = 0;
        while (b) {int t = a / b; a -= t * b; swap(a, b); u -= t * v; swap(u, v);}
        val = val * u % mod; if (val < 0) val += mod;
        return *this;
    }
    Modint &operator /=(const int &q) {
        Modint r(q); int a = r.val, b = mod, u = 1, v = 0;
        while (b) {int t = a / b; a -= t * b; swap(a, b); u -= t * v; swap(u, v);}
        val = val * u % mod; if (val < 0) val += mod;
        return *this;
    }
    bool operator ==(const Modint& r) { return this -> val == r.val; }
    bool operator <(const Modint& r) { return this -> val < r.val; }
    bool operator >(const Modint& r) { return this -> val > r.val; }
    bool operator !=(const Modint& r) { return this -> val != r.val; }

    friend istream &operator >>(istream &is, Modint& x) {
        int t; is >> t; x = t; return (is);
    }
    friend ostream &operator <<(ostream &os, const Modint& x) {
        return os << x.val;
    }
};
using mint = Modint<MOD>;
 
mint modpow(const mint &x, int n) {
    if (n < 0) return (mint)1 / modpow(x, -n); // 未verify
    assert(n >= 0);
    if (n == 0) return 1;
    mint t = modpow(x, n / 2);
    t = t * t;
    if (n & 1) t = t * x;
    return t;
}
int modpow(__int128_t x, int n, int mod) {
    assert(n >= 0 && mod > 0); // TODO: n <= -1
    __int128_t ret = 1;
    while (n > 0) {
        if (n % 2 == 1) ret = ret * x % mod;
        x = x * x % mod;
        n /= 2;
    }
    return ret;
}
// int modinv(__int128_t x, int mod) { // 
//     assert(mod > 0);
//     // assert(x > 0);
//     if (x == 1 or x == 0) return 1;
//     return mod - modinv(mod % x, mod) * (mod / x) % mod;
// }

vector<mint> _fac, _finv, _inv;
void COMinit(int N) {
    _fac.resize(N + 1); _finv.resize(N + 1);  _inv.resize(N + 1);
    _fac[0] = _fac[1] = 1; _finv[0] = _finv[1] = 1; _inv[1] = 1;
    for (int i = 2; i <= N; i++) {
        _fac[i] = _fac[i-1] * mint(i);
        _inv[i] = -_inv[MOD % i] * mint(MOD / i);
        _finv[i] = _finv[i - 1] * _inv[i];
    }
}
 
mint FAC(int N) {
    if (N < 0) return 0; return _fac[N];
}
mint FACinv(int N) {
    if (N < 0) return 0; return _finv[N];
}
mint COM(int N, int K) {
    if (N < K) return 0; if (N < 0 or K < 0) return 0;
    return _fac[N] * _finv[K] * _finv[N - K];
}
mint COMinv(int N, int K) {
    if (N < K) return 0; if (N < 0 or K < 0) return 0;
    return _finv[N] * _fac[K] * _fac[N - K];
}
mint MCOM(const vector<int> &V) {
    int N = 0;
    for (int i = 0; i < V.size(); i++) N += V[i];
    mint ret = _fac[N];
    for (int i = 0; i < V.size(); i++) ret *= _finv[V[i]];
    return ret;
}
mint PERM(int N, int K) {
    if (N < K) return 0; if (N < 0 or K < 0) return 0;
    return _fac[N] *  _finv[N - K];
}
mint NHK(int N, int K) { // initのサイズに注意
    if (N == 0 && K == 0)  return 1;
    return COM(N + K - 1, K);
}
 
#pragma endregion

int H, W;
bool isvalid(int x, int y) {
    if (x >= 0 && x < H && y >= 0 && y < W) return true;
    else return false;
}

int dist[50][50][50][50];
signed main() {
    while (cin >> W >> H, W) {
        int x1, y1, x2, y2;
        cin >> y1 >> x1 >> y2 >> x2;
        y1--; x1--; y2--; x2--;
        vector<vector<int>> A(H, vector<int>(W));
        for (int i = 0; i < H; i++) {
            for (int j = 0; j < W; j++) {
                cin >> A[i][j];
            }
        }

        const int inf = H*W*H*W + 1;

        // dist[i][j] := 人1がマスi, 人2がマスjにいるような状態までの距離
        for (int i = 0; i < 50; i++) {
            for (int j = 0; j < 50; j++) {
                for (int k = 0; k < 50; k++) {
                    for (int l = 0; l < 50; l++) {
                        dist[i][j][k][l] = inf;
                    }
                }
            }
        }
        dist[x1][y1][x2][y2] = 0;

        queue<tuple<int, int, int, int>> qu;
        qu.emplace(x1, y1, x2, y2);

        while (qu.size()) {
            auto[i1, j1, i2, j2] = qu.front();
            qu.pop();
            
            for (int k = 0; k < 4; k++) {
                int ni1 = i1 + dx[k];
                int nj1 = j1 + dy[k];
                if (!isvalid(ni1, nj1) or A[ni1][nj1] == 1) { // 人1の行き先がない場合はその場に留まる
                    ni1 = i1; nj1 = j1;
                }

                int ni2 = i2 + dx[(k + 2) % 4];
                int nj2 = j2 + dy[(k + 2) % 4];
                if (!isvalid(ni2, nj2) or A[ni2][nj2] == 1) { // 人2の行き先がない場合はその場に留まる
                    ni2 = i2; nj2 = j2;
                }

                if (dist[ni1][nj1][ni2][nj2] > dist[i1][j1][i2][j2] + 1) {
                    dist[ni1][nj1][ni2][nj2] = dist[i1][j1][i2][j2] + 1;
                    qu.emplace(ni1, nj1, ni2, nj2);
                    if (ni1 == ni2 && nj1 == nj2) {
                        qu = queue<tuple<int, int, int, int>>();
                        break;
                    }
                }
            }
        }

        int ans = inf;
        for (int i = 0; i < H; i++) {
            for (int j = 0; j < W; j++) {
                ans = min(ans, dist[i][j][i][j]);
            }
        }
        if (ans >= min(100, inf)) cout << "NA" << endl;
        else cout << ans << endl;
    }
}
accuracy: 1
time_ms: 150
memory_kb: 28024
final_rank: 3

code_snippet: #line 1 "library/my_template.hpp"
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")

#include <bits/stdc++.h>

using namespace std;

using ll = long long;
using pi = pair<ll, ll>;
using vi = vector<ll>;
using u32 = unsigned int;
using u64 = unsigned long long;
using i128 = __int128;

template <class T>
using vc = vector<T>;
template <class T>
using vvc = vector<vc<T>>;
template <class T>
using vvvc = vector<vvc<T>>;
template <class T>
using vvvvc = vector<vvvc<T>>;
template <class T>
using vvvvvc = vector<vvvvc<T>>;
template <class T>
using pq = priority_queue<T>;
template <class T>
using pqg = priority_queue<T, vector<T>, greater<T>>;

#define vec(type, name, ...) vector<type> name(__VA_ARGS__)
#define vv(type, name, h, ...) \
  vector<vector<type>> name(h, vector<type>(__VA_ARGS__))
#define vvv(type, name, h, w, ...)   \
  vector<vector<vector<type>>> name( \
      h, vector<vector<type>>(w, vector<type>(__VA_ARGS__)))
#define vvvv(type, name, a, b, c, ...)       \
  vector<vector<vector<vector<type>>>> name( \
      a, vector<vector<vector<type>>>(       \
             b, vector<vector<type>>(c, vector<type>(__VA_ARGS__))))

// https://trap.jp/post/1224/
#define FOR1(a) for (ll _ = 0; _ < ll(a); ++_)
#define FOR2(i, a) for (ll i = 0; i < ll(a); ++i)
#define FOR3(i, a, b) for (ll i = a; i < ll(b); ++i)
#define FOR4(i, a, b, c) for (ll i = a; i < ll(b); i += (c))
#define FOR1_R(a) for (ll i = (a)-1; i >= ll(0); --i)
#define FOR2_R(i, a) for (ll i = (a)-1; i >= ll(0); --i)
#define FOR3_R(i, a, b) for (ll i = (b)-1; i >= ll(a); --i)
#define FOR4_R(i, a, b, c) for (ll i = (b)-1; i >= ll(a); i -= (c))
#define overload4(a, b, c, d, e, ...) e
#define FOR(...) overload4(__VA_ARGS__, FOR4, FOR3, FOR2, FOR1)(__VA_ARGS__)
#define FOR_R(...) \
  overload4(__VA_ARGS__, FOR4_R, FOR3_R, FOR2_R, FOR1_R)(__VA_ARGS__)

#define FOR_subset(t, s) for (ll t = s; t >= 0; t = (t == 0 ? -1 : (t - 1) & s))
#define all(x) x.begin(), x.end()
#define len(x) ll(x.size())
#define elif else if

#define eb emplace_back
#define mp make_pair
#define mt make_tuple
#define fi first
#define se second

#define stoi stoll

template <typename T, typename U>
T SUM(const vector<U> &A) {
  T sum = 0;
  for (auto &&a: A) sum += a;
  return sum;
}

#define MIN(v) *min_element(all(v))
#define MAX(v) *max_element(all(v))
#define LB(c, x) distance((c).begin(), lower_bound(all(c), (x)))
#define UB(c, x) distance((c).begin(), upper_bound(all(c), (x)))
#define UNIQUE(x) sort(all(x)), x.erase(unique(all(x)), x.end())

int popcnt(int x) { return __builtin_popcount(x); }
int popcnt(u32 x) { return __builtin_popcount(x); }
int popcnt(ll x) { return __builtin_popcountll(x); }
int popcnt(u64 x) { return __builtin_popcountll(x); }
// (0, 1, 2, 3, 4) -> (-1, 0, 1, 1, 2)
int topbit(int x) { return (x == 0 ? -1 : 31 - __builtin_clz(x)); }
int topbit(u32 x) { return (x == 0 ? -1 : 31 - __builtin_clz(x)); }
int topbit(ll x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }
int topbit(u64 x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }
// (0, 1, 2, 3, 4) -> (-1, 0, 1, 0, 2)
int lowbit(int x) { return (x == 0 ? -1 : __builtin_ctz(x)); }
int lowbit(u32 x) { return (x == 0 ? -1 : __builtin_ctz(x)); }
int lowbit(ll x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }
int lowbit(u64 x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }

template <typename T>
T pick(deque<T> &que) {
  T a = que.front();
  que.pop_front();
  return a;
}

template <typename T>
T pick(pq<T> &que) {
  T a = que.top();
  que.pop();
  return a;
}

template <typename T>
T pick(pqg<T> &que) {
  assert(que.size());
  T a = que.top();
  que.pop();
  return a;
}

template <typename T>
T pick(vc<T> &que) {
  assert(que.size());
  T a = que.back();
  que.pop_back();
  return a;
}

template <typename T, typename U>
T ceil(T x, U y) {
  return (x > 0 ? (x + y - 1) / y : x / y);
}

template <typename T, typename U>
T floor(T x, U y) {
  return (x > 0 ? x / y : (x - y + 1) / y);
}

template <typename T, typename U>
pair<T, T> divmod(T x, U y) {
  T q = floor(x, y);
  return {q, x - q * y};
}

template <typename F>
ll binary_search(F check, ll ok, ll ng) {
  assert(check(ok));
  while (abs(ok - ng) > 1) {
    auto x = (ng + ok) / 2;
    tie(ok, ng) = (check(x) ? mp(x, ng) : mp(ok, x));
  }
  return ok;
}

template <typename F>
double binary_search_real(F check, double ok, double ng, int iter = 100) {
  FOR(iter) {
    double x = (ok + ng) / 2;
    tie(ok, ng) = (check(x) ? mp(x, ng) : mp(ok, x));
  }
  return (ok + ng) / 2;
}

template <class T, class S>
inline bool chmax(T &a, const S &b) {
  return (a < b ? a = b, 1 : 0);
}
template <class T, class S>
inline bool chmin(T &a, const S &b) {
  return (a > b ? a = b, 1 : 0);
}

vc<int> s_to_vi(const string &S, char first_char) {
  vc<int> A(S.size());
  FOR(i, S.size()) { A[i] = S[i] - first_char; }
  return A;
}

template <typename T, typename U>
vector<T> cumsum(vector<U> &A, int off = 1) {
  int N = A.size();
  vector<T> B(N + 1);
  FOR(i, N) { B[i + 1] = B[i] + A[i]; }
  if (off == 0) B.erase(B.begin());
  return B;
}

template <typename CNT, typename T>
vc<CNT> bincount(const vc<T> &A, int size) {
  vc<CNT> C(size);
  for (auto &&x: A) { ++C[x]; }
  return C;
}

// stable
template <typename T>
vector<int> argsort(const vector<T> &A) {
  vector<int> ids(A.size());
  iota(all(ids), 0);
  sort(all(ids),
       [&](int i, int j) { return A[i] < A[j] || (A[i] == A[j] && i < j); });
  return ids;
}

// A[I[0]], A[I[1]], ...
template <typename T>
vc<T> rearrange(const vc<T> &A, const vc<int> &I) {
  int n = len(I);
  vc<T> B(n);
  FOR(i, n) B[i] = A[I[i]];
  return B;
}
#line 1 "library/other/io.hpp"
// based on yosupo's fastio
#include <unistd.h>

namespace detail {
template <typename T, decltype(&T::is_modint) = &T::is_modint>
std::true_type check_value(int);
template <typename T>
std::false_type check_value(long);
} // namespace detail

template <typename T>
struct is_modint : decltype(detail::check_value<T>(0)) {};
template <typename T>
using is_modint_t = enable_if_t<is_modint<T>::value>;
template <typename T>
using is_not_modint_t = enable_if_t<!is_modint<T>::value>;

struct Scanner {
  FILE *fp;
  char line[(1 << 15) + 1];
  size_t st = 0, ed = 0;
  void reread() {
    memmove(line, line + st, ed - st);
    ed -= st;
    st = 0;
    ed += fread(line + ed, 1, (1 << 15) - ed, fp);
    line[ed] = '\0';
  }
  bool succ() {
    while (true) {
      if (st == ed) {
        reread();
        if (st == ed) return false;
      }
      while (st != ed && isspace(line[st])) st++;
      if (st != ed) break;
    }
    if (ed - st <= 50) {
      bool sep = false;
      for (size_t i = st; i < ed; i++) {
        if (isspace(line[i])) {
          sep = true;
          break;
        }
      }
      if (!sep) reread();
    }
    return true;
  }
  template <class T, enable_if_t<is_same<T, string>::value, int> = 0>
  bool read_single(T &ref) {
    if (!succ()) return false;
    while (true) {
      size_t sz = 0;
      while (st + sz < ed && !isspace(line[st + sz])) sz++;
      ref.append(line + st, sz);
      st += sz;
      if (!sz || st != ed) break;
      reread();
    }
    return true;
  }
  template <class T, enable_if_t<is_integral<T>::value, int> = 0>
  bool read_single(T &ref) {
    if (!succ()) return false;
    bool neg = false;
    if (line[st] == '-') {
      neg = true;
      st++;
    }
    ref = T(0);
    while (isdigit(line[st])) { ref = 10 * ref + (line[st++] & 0xf); }
    if (neg) ref = -ref;
    return true;
  }
  template <class T, is_modint_t<T> * = nullptr>
  bool read_single(T &ref) {
    long long val = 0;
    bool f = read_single(val);
    ref = T(val);
    return f;
  }
  bool read_single(double &ref) {
    string s;
    if (!read_single(s)) return false;
    ref = std::stod(s);
    return true;
  }
  bool read_single(char &ref) {
    string s;
    if (!read_single(s) || s.size() != 1) return false;
    ref = s[0];
    return true;
  }
  template <class T>
  bool read_single(vector<T> &ref) {
    for (auto &d: ref) {
      if (!read_single(d)) return false;
    }
    return true;
  }
  template <class T, class U>
  bool read_single(pair<T, U> &p) {
    return (read_single(p.first) && read_single(p.second));
  }
  template <class A, class B, class C>
  bool read_single(tuple<A, B, C> &p) {
    return (read_single(get<0>(p)) && read_single(get<1>(p))
            && read_single(get<2>(p)));
  }
  template <class A, class B, class C, class D>
  bool read_single(tuple<A, B, C, D> &p) {
    return (read_single(get<0>(p)) && read_single(get<1>(p))
            && read_single(get<2>(p)) && read_single(get<3>(p)));
  }
  void read() {}
  template <class H, class... T>
  void read(H &h, T &... t) {
    bool f = read_single(h);
    assert(f);
    read(t...);
  }
  Scanner(FILE *fp) : fp(fp) {}
};

struct Printer {
  Printer(FILE *_fp) : fp(_fp) {}
  ~Printer() { flush(); }

  static constexpr size_t SIZE = 1 << 15;
  FILE *fp;
  char line[SIZE], small[50];
  size_t pos = 0;
  void flush() {
    fwrite(line, 1, pos, fp);
    pos = 0;
  }
  void write(const char &val) {
    if (pos == SIZE) flush();
    line[pos++] = val;
  }
  template <class T, enable_if_t<is_integral<T>::value, int> = 0>
  void write(T val) {
    if (pos > (1 << 15) - 50) flush();
    if (val == 0) {
      write('0');
      return;
    }
    if (val < 0) {
      write('-');
      val = -val; // todo min
    }
    size_t len = 0;
    while (val) {
      small[len++] = char(0x30 | (val % 10));
      val /= 10;
    }
    for (size_t i = 0; i < len; i++) { line[pos + i] = small[len - 1 - i]; }
    pos += len;
  }
  void write(const string &s) {
    for (char c: s) write(c);
  }
  void write(const char *s) {
    size_t len = strlen(s);
    for (size_t i = 0; i < len; i++) write(s[i]);
  }
  void write(const double &x) {
    ostringstream oss;
    oss << fixed << setprecision(15) << x;
    string s = oss.str();
    write(s);
  }
  void write(const long double &x) {
    ostringstream oss;
    oss << fixed << setprecision(15) << x;
    string s = oss.str();
    write(s);
  }
  template <class T, is_modint_t<T> * = nullptr>
  void write(T &ref) {
    write(ref.val);
  }
  template <class T>
  void write(const vector<T> &val) {
    auto n = val.size();
    for (size_t i = 0; i < n; i++) {
      if (i) write(' ');
      write(val[i]);
    }
  }
  template <class T, class U>
  void write(const pair<T, U> &val) {
    write(val.first);
    write(' ');
    write(val.second);
  }
  template <class A, class B, class C>
  void write(const tuple<A, B, C> &val) {
    auto &[a, b, c] = val;
    write(a), write(' '), write(b), write(' '), write(c);
  }
  template <class A, class B, class C, class D>
  void write(const tuple<A, B, C, D> &val) {
    auto &[a, b, c, d] = val;
    write(a), write(' '), write(b), write(' '), write(c), write(' '), write(d);
  }
  template <class A, class B, class C, class D, class E>
  void write(const tuple<A, B, C, D, E> &val) {
    auto &[a, b, c, d, e] = val;
    write(a), write(' '), write(b), write(' '), write(c), write(' '), write(d), write(' '), write(e);
  }
  template <class A, class B, class C, class D, class E, class F>
  void write(const tuple<A, B, C, D, E, F> &val) {
    auto &[a, b, c, d, e, f] = val;
    write(a), write(' '), write(b), write(' '), write(c), write(' '), write(d), write(' '), write(e), write(' '), write(f);
  }
  template <class T, size_t S>
  void write(const array<T, S> &val) {
    auto n = val.size();
    for (size_t i = 0; i < n; i++) {
      if (i) write(' ');
      write(val[i]);
    }
  }
  void write(i128 val) {
    string s;
    bool negative = 0;
    if(val < 0){
      negative = 1;
      val = -val;
    }
    while (val) {
      s += '0' + int(val % 10);
      val /= 10;
    }
    if(negative) s += "-";
    reverse(all(s));
    if (len(s) == 0) s = "0";
    write(s);
  }
};

Scanner scanner = Scanner(stdin);
Printer printer = Printer(stdout);

void flush() { printer.flush(); }
void print() { printer.write('\n'); }
template <class Head, class... Tail>
void print(Head &&head, Tail &&... tail) {
  printer.write(head);
  if (sizeof...(Tail)) printer.write(' ');
  print(forward<Tail>(tail)...);
}

void read() {}
template <class Head, class... Tail>
void read(Head &head, Tail &... tail) {
  scanner.read(head);
  read(tail...);
}

#define INT(...)   \
  int __VA_ARGS__; \
  read(__VA_ARGS__)
#define LL(...)   \
  ll __VA_ARGS__; \
  read(__VA_ARGS__)
#define STR(...)      \
  string __VA_ARGS__; \
  read(__VA_ARGS__)
#define CHAR(...)      \
  char __VA_ARGS__; \
  read(__VA_ARGS__)
#define DBL(...)      \
  double __VA_ARGS__; \
  read(__VA_ARGS__)

#define VEC(type, name, size) \
  vector<type> name(size);    \
  read(name)
#define VV(type, name, h, w)                     \
  vector<vector<type>> name(h, vector<type>(w)); \
  read(name)

void YES(bool t = 1) { print(t ? "YES" : "NO"); }
void NO(bool t = 1) { YES(!t); }
void Yes(bool t = 1) { print(t ? "Yes" : "No"); }
void No(bool t = 1) { Yes(!t); }
void yes(bool t = 1) { print(t ? "yes" : "no"); }
void no(bool t = 1) { yes(!t); }
#line 3 "main.cpp"

void solve() {
  auto solve = [&](ll H, ll W) -> void {
    LL(ay, ax, by, bx);
    --ay, --ax, --by, --bx;
    VV(int, G, H, W);
    auto isin = [&](ll x, ll y) -> bool {
      return (0 <= x && x < H && 0 <= y && y < W && G[x][y] == 0);
    };
    ll dx[] = {1, 0, -1, 0};
    ll dy[] = {0, 1, 0, -1};
    const ll INF = 1LL << 60;
    vvvv(ll, dp, H, W, H, W, INF);
    using T = tuple<int, int, int, int>;
    deque<T> que;
    auto add = [&](int x1, int y1, int x2, int y2, int d) -> void {
      if (chmin(dp[x1][y1][x2][y2], d)) { que.eb(x1, y1, x2, y2); }
    };
    add(ax, ay, bx, by, 0);
    while (len(que)) {
      auto [x1, y1, x2, y2] = pick(que);
      FOR(d, 4) {
        ll nx1 = x1 + dx[d];
        ll ny1 = y1 + dy[d];
        ll nx2 = x2 - dx[d];
        ll ny2 = y2 - dy[d];
        if (!isin(nx1, ny1)) nx1 = x1, ny1 = y1;
        if (!isin(nx2, ny2)) nx2 = x2, ny2 = y2;
        add(nx1, ny1, nx2, ny2, dp[x1][y1][x2][y2] + 1);
      }
    }
    ll ANS = INF;
    FOR(x, H) FOR(y, W) chmin(ANS, dp[x][y][x][y]);
    if (ANS == INF)
      print("NA");
    else
      print(ANS);
  };

  while (1) {
    LL(W, H);
    if (H + W == 0) break;
    solve(H, W);
  }
}

signed main() {
  cin.tie(nullptr);
  ios::sync_with_stdio(false);
  cout << setprecision(15);

  solve();

  return 0;
}
accuracy: 1
time_ms: 2730
memory_kb: 58204
final_rank: 20

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

#define REP(i, n) for (int i = 0; i < (int)(n); i++)
#define ALL(x) (x).begin(), (x).end()

using namespace std;

template <typename T>
T &chmin(T &a, const T &b) { return a = min(a, b); }
template <typename T>
T &chmax(T &a, const T &b) { return a = max(a, b); }

using ll = long long;
using ld = long double;

const int INF = 1e9;
const ld eps = 1e-9, pi = acos(-1.0);

int w, h;
vector<vector<int>> d;
vector<vector<vector<vector<int>>>> flg;
int movel(int x, int y)
{
    if (d[x - 1][y] == 1)
        return x;
    return x - 1;
}
int mover(int x, int y)
{
    if (d[x + 1][y] == 1)
        return x;
    return x + 1;
}
int moveu(int x, int y)
{
    if (d[x][y - 1] == 1)
        return y;
    return y - 1;
}
int moved(int x, int y)
{
    if (d[x][y + 1] == 1)
        return y;
    return y + 1;
}

int bfs(int tx, int ty, int kx, int ky)
{
    flg.assign(w + 2, vector<vector<vector<int>>>(h + 2, vector<vector<int>>(w + 2, vector<int>(h + 2, 0))));
    queue<vector<int>> q;
    q.push({tx, ty, kx, ky, 0});
    flg[tx][ty][kx][ky] = 1;

    while (!q.empty())
    {
        int vtx = q.front()[0];
        int vty = q.front()[1];
        int vkx = q.front()[2];
        int vky = q.front()[3];
        int vcnt = q.front()[4];
        q.pop();

        if (vtx == vkx && vty == vky)
            return vcnt;
        if (vcnt + 1 + 1 <= 100)
        {
            if (1 != flg[mover(vtx, vty)][vty][movel(vkx, vky)][vky])
            {
                q.push({mover(vtx, vty), vty, movel(vkx, vky), vky, vcnt + 1});
                flg[mover(vtx, vty)][vty][movel(vkx, vky)][vky] = 1;
            }
            if (1 != flg[movel(vtx, vty)][vty][mover(vkx, vky)][vky])
            {
                q.push({movel(vtx, vty), vty, mover(vkx, vky), vky, vcnt + 1});
                flg[mover(vtx, vty)][vty][movel(vkx, vky)][vky] = 1;
            }
            if (1 != flg[vtx][moveu(vtx, vty)][vkx][moved(vkx, vky)])
            {
                q.push({vtx, moveu(vtx, vty), vkx, moved(vkx, vky), vcnt + 1});
                flg[vtx][moveu(vtx, vty)][vkx][moved(vkx, vky)] = 1;
            }
            if (1 != flg[vtx][moved(vtx, vty)][vkx][moveu(vkx, vky)])
            {
                q.push({vtx, moved(vtx, vty), vkx, moveu(vkx, vky), vcnt + 1});
                flg[vtx][moved(vtx, vty)][vkx][moveu(vkx, vky)] = 1;
            }
        }
    }
    return -1;
}

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

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

        int tx, ty, kx, ky;
        cin >> tx >> ty;
        cin >> kx >> ky;
        d.assign(w + 2, vector<int>(h + 2, 1));
        for (int i = 1; i <= h; i++)
        {
            for (int j = 1; j <= w; j++)
            {
                cin >> d[j][i];
            }
        }
        int ans = bfs(tx, ty, kx, ky);
        if (ans == -1)
        {
            cout << "NA" << endl;
        }
        else
        {
            cout << ans << endl;
        }
    }
    return 0;
}
accuracy: 1
time_ms: 250
memory_kb: 47272
final_rank: 7

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

int main(){
    int w, h;
    while(cin >> w >> h, h){
        vector<vector<int>> A(h, vector<int>(w));
        int sy, sx, ty, tx, y1, y2, x1, x2, ny1, ny2, nx1, nx2;
        cin >> sx >> sy >> tx >> ty;
        sx--, sy--, tx--, ty--;
        for(int y = 0; y < h; y++){
            for(int x = 0; x < w; x++){
                cin >> A[y][x];
            }
        }
        vector<vector<vector<vector<int>>>> dp(h, vector<vector<vector<int>>>(w, 
                vector<vector<int>>(h, vector<int>(w, 1 << 30))));
        queue<tuple<int,int,int,int>> nxt;
        dp[sy][sx][ty][tx] = 0;
        nxt.emplace(sy, sx, ty, tx);
        int ans = -1;
        while(!nxt.empty()){
            tie(y1, x1, y2, x2) = nxt.front();
            nxt.pop();
            if(y1 == y2 && x1 == x2){
                ans = dp[y1][x1][y2][x2];
                break;
            }
            for(int i = 0; i < 4; i++){
                int dy = (i == 0) - (i == 1);
                int dx = (i == 2) - (i == 3);
                if(y1 + dy < 0 || y1 + dy >= h || x1 + dx < 0 || x1 + dx >= w || A[y1 + dy][x1 + dx] == 1){
                    ny1 = y1, nx1 = x1;
                }else{
                    ny1 = y1 + dy, nx1 = x1 + dx;
                }
                if(y2 - dy < 0 || y2 - dy >= h || x2 - dx < 0 || x2 - dx >= w || A[y2 - dy][x2 - dx] == 1){
                    ny2 = y2, nx2 = x2;
                }else{
                    ny2 = y2 - dy, nx2 = x2 - dx;
                }
                if(dp[y1][x1][y2][x2] + 1 < dp[ny1][nx1][ny2][nx2]){
                    dp[ny1][nx1][ny2][nx2] = dp[y1][x1][y2][x2] + 1;
                    nxt.emplace(ny1, nx1, ny2, nx2);
                }
            }
        }
        if(ans == -1)cout << "NA" << '\n';
        else cout << ans << '\n';
    }
}
accuracy: 1
time_ms: 280
memory_kb: 32296
final_rank: 5

code_snippet: #define _USE_MATH_DEFINES
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<queue>
#include<set>
#include<map>
#include<unordered_set>
#include<unordered_map>
#include<list>
#include<algorithm>
#include<numeric>
#include<cmath>
#include<climits>
#include<iomanip>
#include<cctype>
#include<sstream>
#include<regex>
#include<bitset>
#include<random>
#include<complex>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
constexpr int mod=1e9+7;
constexpr int Mod=998244353;
constexpr int inf=mod;
constexpr ll linf=(ll)mod*mod;
struct fastio{
	fastio(){
		cin.tie(0);
		ios::sync_with_stdio(0);
		cout<<fixed<<setprecision(20);
	};
}fio;
template<class T>
bool chmax(T&a,const T&b){
	if(a<b){
		a=b;
		return 1;
	}
	return 0;
}
template<class T>
bool chmin(T&a,const T&b){
	if(a>b){
		a=b;
		return 1;
	}
	return 0;
}
typedef pair<int,int>P;
constexpr int dx[]={1,0,0,-1},dy[]={0,1,-1,0};
int dist[2500][2500];
int main(){
	int h,w;
	while(cin>>w>>h,h){
		int tx,ty,kx,ky;
		bool d[50][50];
		cin>>ty>>tx>>ky>>kx;
		ty--,tx--,ky--,kx--;
		for(int i=0;i<h;i++)
			for(int j=0;j<w;j++)
				cin>>d[i][j];
		for(int i=0;i<h*w;i++)
			for(int j=0;j<h*w;j++)
				dist[i][j]=-1;
		queue<P>que;
		que.push({tx*w+ty,kx*w+ky});
		dist[tx*w+ty][kx*w+ky]=0;
		bool fnd=0;
		while(!que.empty()){
			tx=que.front().first/w;
			ty=que.front().first%w;
			kx=que.front().second/w;
			ky=que.front().second%w;
			que.pop();
			if(tx==kx&&ty==ky){
				cout<<dist[tx*w+ty][kx*w+ky]<<endl;
				fnd=1;
				break;
			}
			for(int i=0;i<4;i++){
				int ntx=tx+dx[i],nty=ty+dy[i],nkx=kx+dx[3-i],nky=ky+dy[3-i];
				if(ntx<0||h<=ntx||nty<0||w<=nty||d[ntx][nty]){
					ntx-=dx[i];
					nty-=dy[i];
				}
				if(nkx<0||h<=nkx||nky<0||w<=nky||d[nkx][nky]){
					nkx-=dx[3-i];
					nky-=dy[3-i];
				}
				if(dist[ntx*w+nty][nkx*w+nky]==-1){
					dist[ntx*w+nty][nkx*w+nky]=dist[tx*w+ty][kx*w+ky]+1;
					que.push({ntx*w+nty,nkx*w+nky});
				}
			}
		}
		if(!fnd)
			cout<<"NA"<<endl;
	}
}
accuracy: 1
time_ms: 100
memory_kb: 27940
final_rank: 2

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using VI = vector<int>;
using VL = vector<ll>;
using VS = vector<string>;
template<class T> using PQ = priority_queue<T, vector<T>, greater<T>>;
#define FOR(i,a,n) for(int i=(a);i<(n);++i)
#define eFOR(i,a,n) for(int i=(a);i<=(n);++i)
#define rFOR(i,a,n) for(int i=(n)-1;i>=(a);--i)
#define erFOR(i,a,n) for(int i=(n);i>=(a);--i)
#define SORT(a) sort(a.begin(),a.end())
#define rSORT(a) sort(a.rbegin(),a.rend())
#define fSORT(a,f) sort(a.begin(),a.end(),f)
#define all(a) a.begin(),a.end()
#define out(y,x) ((y)<0||h<=(y)||(x)<0||w<=(x))
#define tp(a,i) get<i>(a)
#ifdef _DEBUG
#define line cout << "-----------------------------\n"
#define stop system("pause")
#endif
constexpr ll INF = 1000000000;
constexpr ll LLINF = 1LL << 60;
constexpr ll mod = 1000000007;
constexpr ll MOD = 998244353;
constexpr ld eps = 1e-10;
constexpr ld pi = 3.1415926535897932;
template<class T>inline bool chmax(T& a, const T& b) { if (a < b) { a = b; return true; }return false; }
template<class T>inline bool chmin(T& a, const T& b) { if (a > b) { a = b; return true; }return false; }
inline void init() { cin.tie(nullptr); cout.tie(nullptr); ios::sync_with_stdio(false); cout << fixed << setprecision(15); }
template<class T>inline istream& operator>>(istream& is, vector<T>& v) { for (auto& a : v)is >> a; return is; }
template<class T, class U>inline istream& operator>>(istream& is, pair<T, U>& p) { is >> p.first >> p.second; return is; }
template<class T>inline vector<T> vec(size_t a) { return vector<T>(a); }
template<class T>inline vector<T> defvec(T def, size_t a) { return vector<T>(a, def); }
template<class T, class... Ts>inline auto vec(size_t a, Ts... ts) { return vector<decltype(vec<T>(ts...))>(a, vec<T>(ts...)); }
template<class T, class... Ts>inline auto defvec(T def, size_t a, Ts... ts) { return vector<decltype(defvec<T>(def, ts...))>(a, defvec<T>(def, ts...)); }
template<class T>inline void print(const T& a) { cout << a << "\n"; }
template<class T, class... Ts>inline void print(const T& a, const Ts&... ts) { cout << a << " "; print(ts...); }
template<class T>inline void print(const vector<T>& v) { for (int i = 0; i < v.size(); ++i)cout << v[i] << (i == v.size() - 1 ? "\n" : " "); }
template<class T>inline void print(const vector<vector<T>>& v) { for (auto& a : v)print(a); }
inline string reversed(const string& s) { string t = s; reverse(all(t)); return t; }
template<class T>inline T sum(const vector<T>& a, int l, int r) { return a[r] - (l == 0 ? 0 : a[l - 1]); }
template<class T>inline void END(T s) { print(s); exit(0); }
void END() { exit(0); }

int d[50][50];
int main() {
    init();

    queue<tuple<int, int, int, int>> bfs;
    int dy[] = { -1,0,0,1 }, dx[] = { 0,-1,1,0 };
    int rdy[] = { 1,0,0,-1 }, rdx[] = { 0,1,-1,0 };
    auto dp = vec<int>(0, 0, 0, 0);
    for (int w, h; cin >> w >> h, w;) {
        int tx, ty, kx, ky; cin >> tx >> ty >> kx >> ky;
        --tx, --ty, --kx, --ky;
        FOR(i, 0, h)FOR(j, 0, w)cin >> d[i][j];
        defvec<int>(INF, h, w, h, w).swap(dp);
        dp[ty][tx][ky][kx] = 0;
        bfs.emplace(ty, tx, ky, kx);
        while (!bfs.empty()) {
            tie(ty, tx, ky, kx) = bfs.front();
            bfs.pop();
            FOR(i, 0, 4) {
                int nty = ty + dy[i], ntx = tx + dx[i];
                if (out(nty, ntx))nty = ty, ntx = tx;
                if (d[nty][ntx])nty = ty, ntx = tx;
                int nky = ky + rdy[i], nkx = kx + rdx[i];
                if (out(nky, nkx))nky = ky, nkx = kx;
                if (d[nky][nkx])nky = ky, nkx = kx;
                if (chmin(dp[nty][ntx][nky][nkx], dp[ty][tx][ky][kx] + 1) && dp[nty][ntx][nky][nkx] < 49)
                    bfs.emplace(nty, ntx, nky, nkx);
            }
        }
        int ans = INF;
        FOR(i, 0, h)FOR(j, 0, w)chmin(ans, dp[i][j][i][j]);
        if (ans == INF)print("NA");
        else print(ans);
    }

    return 0;
}
accuracy: 1
time_ms: 700
memory_kb: 60776
final_rank: 12

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using VI = vector<int>;
using VL = vector<ll>;
using VS = vector<string>;
template<class T> using PQ = priority_queue<T, vector<T>, greater<T>>;
#define FOR(i,a,n) for(int i=(a);i<(n);++i)
#define eFOR(i,a,n) for(int i=(a);i<=(n);++i)
#define rFOR(i,a,n) for(int i=(n)-1;i>=(a);--i)
#define erFOR(i,a,n) for(int i=(n);i>=(a);--i)
#define SORT(a) sort(a.begin(),a.end())
#define rSORT(a) sort(a.rbegin(),a.rend())
#define fSORT(a,f) sort(a.begin(),a.end(),f)
#define all(a) a.begin(),a.end()
#define out(y,x) ((y)<0||h<=(y)||(x)<0||w<=(x))
#define tp(a,i) get<i>(a)
#ifdef _DEBUG
#define line cout << "-----------------------------\n"
#define stop system("pause")
#endif
constexpr ll INF = 1000000000;
constexpr ll LLINF = 1LL << 60;
constexpr ll mod = 1000000007;
constexpr ll MOD = 998244353;
constexpr ld eps = 1e-10;
constexpr ld pi = 3.1415926535897932;
template<class T>inline bool chmax(T& a, const T& b) { if (a < b) { a = b; return true; }return false; }
template<class T>inline bool chmin(T& a, const T& b) { if (a > b) { a = b; return true; }return false; }
inline void init() { cin.tie(nullptr); cout.tie(nullptr); ios::sync_with_stdio(false); cout << fixed << setprecision(15); }
template<class T>inline istream& operator>>(istream& is, vector<T>& v) { for (auto& a : v)is >> a; return is; }
template<class T, class U>inline istream& operator>>(istream& is, pair<T, U>& p) { is >> p.first >> p.second; return is; }
template<class T>inline vector<T> vec(size_t a) { return vector<T>(a); }
template<class T>inline vector<T> defvec(T def, size_t a) { return vector<T>(a, def); }
template<class T, class... Ts>inline auto vec(size_t a, Ts... ts) { return vector<decltype(vec<T>(ts...))>(a, vec<T>(ts...)); }
template<class T, class... Ts>inline auto defvec(T def, size_t a, Ts... ts) { return vector<decltype(defvec<T>(def, ts...))>(a, defvec<T>(def, ts...)); }
template<class T>inline void print(const T& a) { cout << a << "\n"; }
template<class T, class... Ts>inline void print(const T& a, const Ts&... ts) { cout << a << " "; print(ts...); }
template<class T>inline void print(const vector<T>& v) { for (int i = 0; i < v.size(); ++i)cout << v[i] << (i == v.size() - 1 ? "\n" : " "); }
template<class T>inline void print(const vector<vector<T>>& v) { for (auto& a : v)print(a); }
inline string reversed(const string& s) { string t = s; reverse(all(t)); return t; }
template<class T>inline T sum(const vector<T>& a, int l, int r) { return a[r] - (l == 0 ? 0 : a[l - 1]); }
template<class T>inline void END(T s) { print(s); exit(0); }
void END() { exit(0); }

int main() {
    init();

    queue<tuple<int, int, int, int>> bfs;
    int dy[] = { -1,0,0,1 }, dx[] = { 0,-1,1,0 };
    int rdy[] = { 1,0,0,-1 }, rdx[] = { 0,1,-1,0 };
    auto d = vec<int>(0, 0);
    auto dp = vec<int>(0, 0, 0, 0);
    for (int w, h; cin >> w >> h, w;) {
        int tx, ty, kx, ky; cin >> tx >> ty >> kx >> ky;
        --tx, --ty, --kx, --ky;
        vec<int>(h, w).swap(d); cin >> d;
        defvec<int>(INF, h, w, h, w).swap(dp);
        dp[ty][tx][ky][kx] = 0;
        bfs.emplace(ty, tx, ky, kx);
        while (!bfs.empty()) {
            tie(ty, tx, ky, kx) = bfs.front();
            bfs.pop();
            FOR(i, 0, 4) {
                int nty = ty + dy[i], ntx = tx + dx[i];
                if (out(nty, ntx))nty = ty, ntx = tx;
                if (d[nty][ntx])nty = ty, ntx = tx;
                int nky = ky + rdy[i], nkx = kx + rdx[i];
                if (out(nky, nkx))nky = ky, nkx = kx;
                if (d[nky][nkx])nky = ky, nkx = kx;
                if (chmin(dp[nty][ntx][nky][nkx], dp[ty][tx][ky][kx] + 1) && dp[nty][ntx][nky][nkx] < 49)
                    bfs.emplace(nty, ntx, nky, nkx);
            }
        }
        int ans = INF;
        FOR(i, 0, h)FOR(j, 0, w)chmin(ans, dp[i][j][i][j]);
        if (ans == INF)print("NA");
        else print(ans);
    }

    return 0;
}
accuracy: 1
time_ms: 690
memory_kb: 60816
final_rank: 10

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using VI = vector<int>;
using VL = vector<ll>;
using VS = vector<string>;
template<class T> using PQ = priority_queue<T, vector<T>, greater<T>>;
#define FOR(i,a,n) for(int i=(a);i<(n);++i)
#define eFOR(i,a,n) for(int i=(a);i<=(n);++i)
#define rFOR(i,a,n) for(int i=(n)-1;i>=(a);--i)
#define erFOR(i,a,n) for(int i=(n);i>=(a);--i)
#define SORT(a) sort(a.begin(),a.end())
#define rSORT(a) sort(a.rbegin(),a.rend())
#define fSORT(a,f) sort(a.begin(),a.end(),f)
#define all(a) a.begin(),a.end()
#define out(y,x) ((y)<0||h<=(y)||(x)<0||w<=(x))
#define tp(a,i) get<i>(a)
#ifdef _DEBUG
#define line cout << "-----------------------------\n"
#define stop system("pause")
#endif
constexpr ll INF = 1000000000;
constexpr ll LLINF = 1LL << 60;
constexpr ll mod = 1000000007;
constexpr ll MOD = 998244353;
constexpr ld eps = 1e-10;
constexpr ld pi = 3.1415926535897932;
template<class T>inline bool chmax(T& a, const T& b) { if (a < b) { a = b; return true; }return false; }
template<class T>inline bool chmin(T& a, const T& b) { if (a > b) { a = b; return true; }return false; }
inline void init() { cin.tie(nullptr); cout.tie(nullptr); ios::sync_with_stdio(false); cout << fixed << setprecision(15); }
template<class T>inline istream& operator>>(istream& is, vector<T>& v) { for (auto& a : v)is >> a; return is; }
template<class T, class U>inline istream& operator>>(istream& is, pair<T, U>& p) { is >> p.first >> p.second; return is; }
template<class T>inline vector<T> vec(size_t a) { return vector<T>(a); }
template<class T>inline vector<T> defvec(T def, size_t a) { return vector<T>(a, def); }
template<class T, class... Ts>inline auto vec(size_t a, Ts... ts) { return vector<decltype(vec<T>(ts...))>(a, vec<T>(ts...)); }
template<class T, class... Ts>inline auto defvec(T def, size_t a, Ts... ts) { return vector<decltype(defvec<T>(def, ts...))>(a, defvec<T>(def, ts...)); }
template<class T>inline void print(const T& a) { cout << a << "\n"; }
template<class T, class... Ts>inline void print(const T& a, const Ts&... ts) { cout << a << " "; print(ts...); }
template<class T>inline void print(const vector<T>& v) { for (int i = 0; i < v.size(); ++i)cout << v[i] << (i == v.size() - 1 ? "\n" : " "); }
template<class T>inline void print(const vector<vector<T>>& v) { for (auto& a : v)print(a); }
inline string reversed(const string& s) { string t = s; reverse(all(t)); return t; }
template<class T>inline T sum(const vector<T>& a, int l, int r) { return a[r] - (l == 0 ? 0 : a[l - 1]); }
template<class T>inline void END(T s) { print(s); exit(0); }
void END() { exit(0); }

int main() {
    init();

    queue<tuple<int, int, int, int>> bfs;
    int dy[] = { -1,0,0,1 }, dx[] = { 0,-1,1,0 };
    int rdy[] = { 1,0,0,-1 }, rdx[] = { 0,1,-1,0 };
    auto d = vec<int>(0, 0);
    auto dp = vec<int>(0, 0, 0, 0);
    for (int w, h; cin >> w >> h, w;) {
        int tx, ty, kx, ky; cin >> tx >> ty >> kx >> ky;
        --tx, --ty, --kx, --ky;
        vec<int>(h, w).swap(d); cin >> d;
        defvec<int>(INF, h, w, h, w).swap(dp);
        dp[ty][tx][ky][kx] = 0;
        bfs.emplace(ty, tx, ky, kx);
        while (!bfs.empty()) {
            tie(ty, tx, ky, kx) = bfs.front();
            bfs.pop();
            if (dp[ty][tx][ky][kx] == 49)continue;
            FOR(i, 0, 4) {
                int nty = ty + dy[i], ntx = tx + dx[i];
                if (out(nty, ntx))nty = ty, ntx = tx;
                if (d[nty][ntx])nty = ty, ntx = tx;
                int nky = ky + rdy[i], nkx = kx + rdx[i];
                if (out(nky, nkx))nky = ky, nkx = kx;
                if (d[nky][nkx])nky = ky, nkx = kx;
                if (chmin(dp[nty][ntx][nky][nkx], dp[ty][tx][ky][kx] + 1))
                    bfs.emplace(nty, ntx, nky, nkx);
            }
        }
        int ans = INF;
        FOR(i, 0, h)FOR(j, 0, w)chmin(ans, dp[i][j][i][j]);
        if (ans == INF)print("NA");
        else print(ans);
    }

    return 0;
}
accuracy: 1
time_ms: 690
memory_kb: 60908
final_rank: 11

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using VI = vector<int>;
using VL = vector<ll>;
using VS = vector<string>;
template<class T> using PQ = priority_queue<T, vector<T>, greater<T>>;
#define FOR(i,a,n) for(int i=(a);i<(n);++i)
#define eFOR(i,a,n) for(int i=(a);i<=(n);++i)
#define rFOR(i,a,n) for(int i=(n)-1;i>=(a);--i)
#define erFOR(i,a,n) for(int i=(n);i>=(a);--i)
#define SORT(a) sort(a.begin(),a.end())
#define rSORT(a) sort(a.rbegin(),a.rend())
#define fSORT(a,f) sort(a.begin(),a.end(),f)
#define all(a) a.begin(),a.end()
#define out(y,x) ((y)<0||h<=(y)||(x)<0||w<=(x))
#define tp(a,i) get<i>(a)
#ifdef _DEBUG
#define line cout << "-----------------------------\n"
#define stop system("pause")
#endif
constexpr ll INF = 1000000000;
constexpr ll LLINF = 1LL << 60;
constexpr ll mod = 1000000007;
constexpr ll MOD = 998244353;
constexpr ld eps = 1e-10;
constexpr ld pi = 3.1415926535897932;
template<class T>inline bool chmax(T& a, const T& b) { if (a < b) { a = b; return true; }return false; }
template<class T>inline bool chmin(T& a, const T& b) { if (a > b) { a = b; return true; }return false; }
inline void init() { cin.tie(nullptr); cout.tie(nullptr); ios::sync_with_stdio(false); cout << fixed << setprecision(15); }
template<class T>inline istream& operator>>(istream& is, vector<T>& v) { for (auto& a : v)is >> a; return is; }
template<class T, class U>inline istream& operator>>(istream& is, pair<T, U>& p) { is >> p.first >> p.second; return is; }
template<class T>inline vector<T> vec(size_t a) { return vector<T>(a); }
template<class T>inline vector<T> defvec(T def, size_t a) { return vector<T>(a, def); }
template<class T, class... Ts>inline auto vec(size_t a, Ts... ts) { return vector<decltype(vec<T>(ts...))>(a, vec<T>(ts...)); }
template<class T, class... Ts>inline auto defvec(T def, size_t a, Ts... ts) { return vector<decltype(defvec<T>(def, ts...))>(a, defvec<T>(def, ts...)); }
template<class T>inline void print(const T& a) { cout << a << "\n"; }
template<class T, class... Ts>inline void print(const T& a, const Ts&... ts) { cout << a << " "; print(ts...); }
template<class T>inline void print(const vector<T>& v) { for (int i = 0; i < v.size(); ++i)cout << v[i] << (i == v.size() - 1 ? "\n" : " "); }
template<class T>inline void print(const vector<vector<T>>& v) { for (auto& a : v)print(a); }
inline string reversed(const string& s) { string t = s; reverse(all(t)); return t; }
template<class T>inline T sum(const vector<T>& a, int l, int r) { return a[r] - (l == 0 ? 0 : a[l - 1]); }
template<class T>inline void END(T s) { print(s); exit(0); }
void END() { exit(0); }

int main() {
    init();

    queue<tuple<int, int, int, int>> bfs;
    int dy[] = { -1,0,0,1 }, dx[] = { 0,-1,1,0 };
    int rdy[] = { 1,0,0,-1 }, rdx[] = { 0,1,-1,0 };
    auto d = vec<int>(0, 0);
    auto dp = vec<int>(0, 0, 0, 0);
    for (int w, h; cin >> w >> h, w;) {
        int tx, ty, kx, ky; cin >> tx >> ty >> kx >> ky;
        --tx, --ty, --kx, --ky;
        vec<int>(h, w).swap(d); cin >> d;
        defvec<int>(INF, h, w, h, w).swap(dp);
        dp[ty][tx][ky][kx] = 0;
        bfs.emplace(ty, tx, ky, kx);
        while (!bfs.empty()) {
            tie(ty, tx, ky, kx) = bfs.front();
            bfs.pop();
            if (dp[ty][tx][ky][kx] == 50)continue;
            FOR(i, 0, 4) {
                int nty = ty + dy[i], ntx = tx + dx[i];
                if (out(nty, ntx))nty = ty, ntx = tx;
                if (d[nty][ntx])nty = ty, ntx = tx;
                int nky = ky + rdy[i], nkx = kx + rdx[i];
                if (out(nky, nkx))nky = ky, nkx = kx;
                if (d[nky][nkx])nky = ky, nkx = kx;
                if (chmin(dp[nty][ntx][nky][nkx], dp[ty][tx][ky][kx] + 1))
                    bfs.emplace(nty, ntx, nky, nkx);
            }
        }
        int ans = INF;
        FOR(i, 0, h)FOR(j, 0, w)chmin(ans, dp[i][j][i][j]);
        if (ans == INF)print("NA");
        else print(ans);
    }

    return 0;
}
accuracy: 1
time_ms: 740
memory_kb: 60740
final_rank: 13

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using VI = vector<int>;
using VL = vector<ll>;
using VS = vector<string>;
template<class T> using PQ = priority_queue<T, vector<T>, greater<T>>;
#define FOR(i,a,n) for(int i=(a);i<(n);++i)
#define eFOR(i,a,n) for(int i=(a);i<=(n);++i)
#define rFOR(i,a,n) for(int i=(n)-1;i>=(a);--i)
#define erFOR(i,a,n) for(int i=(n);i>=(a);--i)
#define SORT(a) sort(a.begin(),a.end())
#define rSORT(a) sort(a.rbegin(),a.rend())
#define fSORT(a,f) sort(a.begin(),a.end(),f)
#define all(a) a.begin(),a.end()
#define out(y,x) ((y)<0||h<=(y)||(x)<0||w<=(x))
#define tp(a,i) get<i>(a)
#ifdef _DEBUG
#define line cout << "-----------------------------\n"
#define stop system("pause")
#endif
constexpr ll INF = 1000000000;
constexpr ll LLINF = 1LL << 60;
constexpr ll mod = 1000000007;
constexpr ll MOD = 998244353;
constexpr ld eps = 1e-10;
constexpr ld pi = 3.1415926535897932;
template<class T>inline bool chmax(T& a, const T& b) { if (a < b) { a = b; return true; }return false; }
template<class T>inline bool chmin(T& a, const T& b) { if (a > b) { a = b; return true; }return false; }
inline void init() { cin.tie(nullptr); cout.tie(nullptr); ios::sync_with_stdio(false); cout << fixed << setprecision(15); }
template<class T>inline istream& operator>>(istream& is, vector<T>& v) { for (auto& a : v)is >> a; return is; }
template<class T, class U>inline istream& operator>>(istream& is, pair<T, U>& p) { is >> p.first >> p.second; return is; }
template<class T>inline vector<T> vec(size_t a) { return vector<T>(a); }
template<class T>inline vector<T> defvec(T def, size_t a) { return vector<T>(a, def); }
template<class T, class... Ts>inline auto vec(size_t a, Ts... ts) { return vector<decltype(vec<T>(ts...))>(a, vec<T>(ts...)); }
template<class T, class... Ts>inline auto defvec(T def, size_t a, Ts... ts) { return vector<decltype(defvec<T>(def, ts...))>(a, defvec<T>(def, ts...)); }
template<class T>inline void print(const T& a) { cout << a << "\n"; }
template<class T, class... Ts>inline void print(const T& a, const Ts&... ts) { cout << a << " "; print(ts...); }
template<class T>inline void print(const vector<T>& v) { for (int i = 0; i < v.size(); ++i)cout << v[i] << (i == v.size() - 1 ? "\n" : " "); }
template<class T>inline void print(const vector<vector<T>>& v) { for (auto& a : v)print(a); }
inline string reversed(const string& s) { string t = s; reverse(all(t)); return t; }
template<class T>inline T sum(const vector<T>& a, int l, int r) { return a[r] - (l == 0 ? 0 : a[l - 1]); }
template<class T>inline void END(T s) { print(s); exit(0); }
void END() { exit(0); }

int main() {
    init();

    queue<tuple<int, int, int, int>> bfs;
    int dy[] = { -1,0,0,1 }, dx[] = { 0,-1,1,0 };
    int rdy[] = { 1,0,0,-1 }, rdx[] = { 0,1,-1,0 };
    auto d = vec<int>(0, 0);
    auto dp = vec<int>(0, 0, 0, 0);
    for (int w, h; cin >> w >> h, w;) {
        int tx, ty, kx, ky; cin >> tx >> ty >> kx >> ky;
        --tx, --ty, --kx, --ky;
        vec<int>(h, w).swap(d); cin >> d;
        defvec<int>(INF, h, w, h, w).swap(dp);
        dp[ty][tx][ky][kx] = 0;
        bfs.emplace(ty, tx, ky, kx);
        while (!bfs.empty()) {
            tie(ty, tx, ky, kx) = bfs.front();
            bfs.pop();
            if (dp[ty][tx][ky][kx] == 80)continue;
            FOR(i, 0, 4) {
                int nty = ty + dy[i], ntx = tx + dx[i];
                if (out(nty, ntx))nty = ty, ntx = tx;
                if (d[nty][ntx])nty = ty, ntx = tx;
                int nky = ky + rdy[i], nkx = kx + rdx[i];
                if (out(nky, nkx))nky = ky, nkx = kx;
                if (d[nky][nkx])nky = ky, nkx = kx;
                if (chmin(dp[nty][ntx][nky][nkx], dp[ty][tx][ky][kx] + 1))
                    bfs.emplace(nty, ntx, nky, nkx);
            }
        }
        int ans = INF;
        FOR(i, 0, h)FOR(j, 0, w)chmin(ans, dp[i][j][i][j]);
        if (ans == INF)print("NA");
        else print(ans);
    }

    return 0;
}
accuracy: 1
time_ms: 1730
memory_kb: 60792
final_rank: 18

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using VI = vector<int>;
using VL = vector<ll>;
using VS = vector<string>;
template<class T> using PQ = priority_queue<T, vector<T>, greater<T>>;
#define FOR(i,a,n) for(int i=(a);i<(n);++i)
#define eFOR(i,a,n) for(int i=(a);i<=(n);++i)
#define rFOR(i,a,n) for(int i=(n)-1;i>=(a);--i)
#define erFOR(i,a,n) for(int i=(n);i>=(a);--i)
#define SORT(a) sort(a.begin(),a.end())
#define rSORT(a) sort(a.rbegin(),a.rend())
#define fSORT(a,f) sort(a.begin(),a.end(),f)
#define all(a) a.begin(),a.end()
#define out(y,x) ((y)<0||h<=(y)||(x)<0||w<=(x))
#define tp(a,i) get<i>(a)
#ifdef _DEBUG
#define line cout << "-----------------------------\n"
#define stop system("pause")
#endif
constexpr ll INF = 1000000000;
constexpr ll LLINF = 1LL << 60;
constexpr ll mod = 1000000007;
constexpr ll MOD = 998244353;
constexpr ld eps = 1e-10;
constexpr ld pi = 3.1415926535897932;
template<class T>inline bool chmax(T& a, const T& b) { if (a < b) { a = b; return true; }return false; }
template<class T>inline bool chmin(T& a, const T& b) { if (a > b) { a = b; return true; }return false; }
inline void init() { cin.tie(nullptr); cout.tie(nullptr); ios::sync_with_stdio(false); cout << fixed << setprecision(15); }
template<class T>inline istream& operator>>(istream& is, vector<T>& v) { for (auto& a : v)is >> a; return is; }
template<class T, class U>inline istream& operator>>(istream& is, pair<T, U>& p) { is >> p.first >> p.second; return is; }
template<class T>inline vector<T> vec(size_t a) { return vector<T>(a); }
template<class T>inline vector<T> defvec(T def, size_t a) { return vector<T>(a, def); }
template<class T, class... Ts>inline auto vec(size_t a, Ts... ts) { return vector<decltype(vec<T>(ts...))>(a, vec<T>(ts...)); }
template<class T, class... Ts>inline auto defvec(T def, size_t a, Ts... ts) { return vector<decltype(defvec<T>(def, ts...))>(a, defvec<T>(def, ts...)); }
template<class T>inline void print(const T& a) { cout << a << "\n"; }
template<class T, class... Ts>inline void print(const T& a, const Ts&... ts) { cout << a << " "; print(ts...); }
template<class T>inline void print(const vector<T>& v) { for (int i = 0; i < v.size(); ++i)cout << v[i] << (i == v.size() - 1 ? "\n" : " "); }
template<class T>inline void print(const vector<vector<T>>& v) { for (auto& a : v)print(a); }
inline string reversed(const string& s) { string t = s; reverse(all(t)); return t; }
template<class T>inline T sum(const vector<T>& a, int l, int r) { return a[r] - (l == 0 ? 0 : a[l - 1]); }
template<class T>inline void END(T s) { print(s); exit(0); }
void END() { exit(0); }

int main() {
    init();

    queue<tuple<int, int, int, int>> bfs;
    int dy[] = { -1,0,0,1 }, dx[] = { 0,-1,1,0 };
    int rdy[] = { 1,0,0,-1 }, rdx[] = { 0,1,-1,0 };
    auto d = vec<int>(0, 0);
    auto dp = vec<int>(0, 0, 0, 0);
    for (int w, h; cin >> w >> h, w;) {
        int tx, ty, kx, ky; cin >> tx >> ty >> kx >> ky;
        --tx, --ty, --kx, --ky;
        vec<int>(h, w).swap(d); cin >> d;
        defvec<int>(INF, h, w, h, w).swap(dp);
        dp[ty][tx][ky][kx] = 0;
        bfs.emplace(ty, tx, ky, kx);
        while (!bfs.empty()) {
            tie(ty, tx, ky, kx) = bfs.front();
            bfs.pop();
            if (dp[ty][tx][ky][kx] == 99)continue;
            FOR(i, 0, 4) {
                int nty = ty + dy[i], ntx = tx + dx[i];
                if (out(nty, ntx))nty = ty, ntx = tx;
                if (d[nty][ntx])nty = ty, ntx = tx;
                int nky = ky + rdy[i], nkx = kx + rdx[i];
                if (out(nky, nkx))nky = ky, nkx = kx;
                if (d[nky][nkx])nky = ky, nkx = kx;
                if (chmin(dp[nty][ntx][nky][nkx], dp[ty][tx][ky][kx] + 1))
                    bfs.emplace(nty, ntx, nky, nkx);
            }
        }
        int ans = INF;
        FOR(i, 0, h)FOR(j, 0, w)chmin(ans, dp[i][j][i][j]);
        if (ans == INF)print("NA");
        else print(ans);
    }

    return 0;
}
accuracy: 1
time_ms: 2190
memory_kb: 60916
final_rank: 19

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using VI = vector<int>;
using VL = vector<ll>;
using VS = vector<string>;
template<class T> using PQ = priority_queue<T, vector<T>, greater<T>>;
#define FOR(i,a,n) for(int i=(a);i<(n);++i)
#define eFOR(i,a,n) for(int i=(a);i<=(n);++i)
#define rFOR(i,a,n) for(int i=(n)-1;i>=(a);--i)
#define erFOR(i,a,n) for(int i=(n);i>=(a);--i)
#define SORT(a) sort(a.begin(),a.end())
#define rSORT(a) sort(a.rbegin(),a.rend())
#define fSORT(a,f) sort(a.begin(),a.end(),f)
#define all(a) a.begin(),a.end()
#define out(y,x) ((y)<0||h<=(y)||(x)<0||w<=(x))
#define tp(a,i) get<i>(a)
#ifdef _DEBUG
#define line cout << "-----------------------------\n"
#define stop system("pause")
#endif
constexpr ll INF = 1000000000;
constexpr ll LLINF = 1LL << 60;
constexpr ll mod = 1000000007;
constexpr ll MOD = 998244353;
constexpr ld eps = 1e-10;
constexpr ld pi = 3.1415926535897932;
template<class T>inline bool chmax(T& a, const T& b) { if (a < b) { a = b; return true; }return false; }
template<class T>inline bool chmin(T& a, const T& b) { if (a > b) { a = b; return true; }return false; }
inline void init() { cin.tie(nullptr); cout.tie(nullptr); ios::sync_with_stdio(false); cout << fixed << setprecision(15); }
template<class T>inline istream& operator>>(istream& is, vector<T>& v) { for (auto& a : v)is >> a; return is; }
template<class T, class U>inline istream& operator>>(istream& is, pair<T, U>& p) { is >> p.first >> p.second; return is; }
template<class T>inline vector<T> vec(size_t a) { return vector<T>(a); }
template<class T>inline vector<T> defvec(T def, size_t a) { return vector<T>(a, def); }
template<class T, class... Ts>inline auto vec(size_t a, Ts... ts) { return vector<decltype(vec<T>(ts...))>(a, vec<T>(ts...)); }
template<class T, class... Ts>inline auto defvec(T def, size_t a, Ts... ts) { return vector<decltype(defvec<T>(def, ts...))>(a, defvec<T>(def, ts...)); }
template<class T>inline void print(const T& a) { cout << a << "\n"; }
template<class T, class... Ts>inline void print(const T& a, const Ts&... ts) { cout << a << " "; print(ts...); }
template<class T>inline void print(const vector<T>& v) { for (int i = 0; i < v.size(); ++i)cout << v[i] << (i == v.size() - 1 ? "\n" : " "); }
template<class T>inline void print(const vector<vector<T>>& v) { for (auto& a : v)print(a); }
inline string reversed(const string& s) { string t = s; reverse(all(t)); return t; }
template<class T>inline T sum(const vector<T>& a, int l, int r) { return a[r] - (l == 0 ? 0 : a[l - 1]); }
template<class T>inline void END(T s) { print(s); exit(0); }
void END() { exit(0); }

int main() {
    init();

    queue<tuple<int, int, int, int>> bfs;
    int dy[] = { -1,0,0,1 }, dx[] = { 0,-1,1,0 };
    int rdy[] = { 1,0,0,-1 }, rdx[] = { 0,1,-1,0 };
    for (int w, h; cin >> w >> h, w;) {
        int tx, ty, kx, ky; cin >> tx >> ty >> kx >> ky;
        --tx, --ty, --kx, --ky;
        auto d = vec<int>(h, w); cin >> d;
        auto dp = defvec<int>(INF, h, w, h, w);
        dp[ty][tx][ky][kx] = 0;
        bfs.emplace(ty, tx, ky, kx);
        while (!bfs.empty()) {
            tie(ty, tx, ky, kx) = bfs.front();
            bfs.pop();
            if (dp[ty][tx][ky][kx] == 99)continue;
            FOR(i, 0, 4) {
                int nty = ty + dy[i], ntx = tx + dx[i];
                if (out(nty, ntx))nty = ty, ntx = tx;
                if (d[nty][ntx])nty = ty, ntx = tx;
                int nky = ky + rdy[i], nkx = kx + rdx[i];
                if (out(nky, nkx))nky = ky, nkx = kx;
                if (d[nky][nkx])nky = ky, nkx = kx;
                if (chmin(dp[nty][ntx][nky][nkx], dp[ty][tx][ky][kx] + 1))
                    bfs.emplace(nty, ntx, nky, nkx);
            }
        }
        int ans = INF;
        FOR(i, 0, h)FOR(j, 0, w)chmin(ans, dp[i][j][i][j]);
        if (ans == INF)print("NA");
        else print(ans);
    }

    return 0;
}
accuracy: 1
time_ms: 2060
memory_kb: 32728
final_rank: 9

code_snippet: #include <bits/stdc++.h>
//#include <atcoder/all>
//using namespace atcoder;
const double pi = 3.141592653589793238462643383279;
using namespace std;
//typedef
//------------------------------------------
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<string> VS;
typedef pair<int, int> PII;
typedef pair<long long, long long> PLL;
typedef pair<int, PII> TIII;
typedef long long LL;
typedef unsigned long long ULL;
typedef vector<LL> VLL;
typedef vector<VLL> VVLL;

//container util
//------------------------------------------
#define ALL(a) (a).begin(), (a).endf()
#define RALL(a) (a).rbegin(), (a).rend()
#define PB push_back
#define MP make_pair
#define SZ(a) int((a).size())
#define SQ(a) ((a) * (a))
#define EACH(i, c) for (typeof((c).begin()) i = (c).begin(); i != (c).endf(); ++i)
#define EXIST(s, e) ((s).find(e) != (s).endf())
#define SORT(c) sort((c).begin(), (c).endf())

//repetition
//------------------------------------------
#define FOR(i, s, n) for (int i = s; i < (int)n; ++i)
#define REP(i, n) FOR(i, 0, n)
#define MOD 1000000007

#define rep(i, a, b) for (int i = a; i < (b); ++i)
#define trav(a, x) for (auto &a : x)
#define all(x) x.begin(), x.end()
#define sz(x) (int)(x).size()

typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;

#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
const double EPS = 1e-4, PI = acos(-1);
//ここから編集    
typedef string::const_iterator State;
int dxy[5]={-1,0,1,0,-1};
int dp[55][55][55][55];
int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    cout << fixed << setprecision(15);

    int W, H;
    while(cin >> W >> H, W&&H){
        int tx,ty,kx,ky;
        cin>>tx>>ty>>kx>>ky;
        tx--; ty--; kx--; ky--;

        vector<vector<int>> f(H, vector<int>(W)); 
        REP(i,H) REP(j,W)cin >> f[i][j];
        REP(i,55)REP(j,55)REP(k,55)REP(l,55) dp[i][j][k][l] = INT_MAX;
        dp[ty][tx][ky][kx] = 0;

        queue<pair<int, int>> q;
        q.push({ty*W+tx, ky*W+kx});
        while(q.size()){
            auto p = q.front();
            q.pop();
            int sy = p.first/W, sx = p.first%W;
            int ssy = p.second/W, ssx = p.second%W;
            for(int i=0; i<4; i++){
                int ny = sy + dxy[i], nx = sx + dxy[i+1];
                int nny,nnx;
                if(i==0){nny = ssy+1;nnx=ssx;}
                else if(i==1){nny=ssy;nnx=ssx-1;}
                else if(i==2){nny=ssy-1;nnx=ssx;}
                else{nny=ssy;nnx=ssx+1;}

                if(!(ny >= 0 && ny < H && nx >= 0 && nx < W && f[ny][nx] != 1)){
                    ny = sy, nx = sx;
                }
                if(!(nny >= 0 && nny < H && nnx >= 0 && nnx < W && f[nny][nnx] != 1)){
                    nny = ssy, nnx = ssx;
                }

                if(dp[ny][nx][nny][nnx] == INT_MAX){
                    dp[ny][nx][nny][nnx] = dp[sy][sx][ssy][ssx] + 1;
                    q.push(make_pair(ny*W+nx, nny*W+nnx));
                }
            }
        }
        int ans = INT_MAX;
        for(int i=0; i<H; i++){
            for(int j=0; j<W; j++){
                ans = min(ans, dp[i][j][i][j]);
            }
        }
        if(ans >= 100) cout << "NA" << endl;
        else cout << ans << endl;
    }

    return 0;
}
accuracy: 1
time_ms: 2620
memory_kb: 39108
final_rank: 17

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

struct st{
    int sy,sx,ty,tx;
    st(int sy, int sx, int ty, int tx):sy(sy),sx(sx),ty(ty),tx(tx){}
};
int dp[52][52][52][52];

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

        int sx,sy,tx,ty;
        cin >> sx >> sy >> tx >> ty;
        vector<vector<int>> g(h+2, vector<int>(w+2, 1));
        for(int i=1; i<=h; i++){
            for(int j=1; j<=w; j++){
                cin >> g[i][j];
            }
        }
        
        queue<st> wait;
        wait.push(st(sy, sx, ty, tx));
        for(int i=0; i<h+2; i++){
            for(int j=0; j<w+2; j++){
                for(int k=0; k<h+2; k++){
                    for(int l=0; l<w+2; l++){
                        dp[i][j][k][l] = inf;
                    }
                }
            }
        }
        dp[sy][sx][ty][tx] = 0;
        int ans = inf;
        while(!wait.empty()){
            int sy = wait.front().sy;
            int sx = wait.front().sx;
            int ty = wait.front().ty;
            int tx = wait.front().tx;
            wait.pop();
            if(sy==ty and sx==tx){
                ans = dp[sy][sx][ty][tx];
                break;
            }
            for(int d=0; d<4; d++){
                int nsy = sy +dy[d];
                int nsx = sx +dx[d];
                int nty = ty +dy[(d+2)%4];
                int ntx = tx +dx[(d+2)%4];
                if(g[nsy][nsx] == 1){
                    nsy = sy;
                    nsx = sx;
                }
                if(g[nty][ntx] == 1){
                    nty = ty;
                    ntx = tx;
                }
                if(dp[nsy][nsx][nty][ntx] == inf){
                    dp[nsy][nsx][nty][ntx] = dp[sy][sx][ty][tx] +1;
                    wait.push(st(nsy, nsx, nty, ntx));
                }
            }
        }
        if(ans >= 100){
            cout << "NA" << endl;
        }else{
            cout << ans << endl;
        }
    }
    return 0;
}
accuracy: 1
time_ms: 170
memory_kb: 31784
final_rank: 4

code_snippet: #include "bits/stdc++.h"

// Begin Header {{{
#pragma region
using namespace std;
using imax = intmax_t;
using usize = size_t;
using ld = long double;

#ifndef DEBUG
#define dump(...)
#endif

#define all(x) begin(x), end(x)
#define rall(x) rbegin(x), rend(x)
#define rep(i, b, e) for (intmax_t i = (b), i##_limit = (e); i < i##_limit; ++i)
#define repc(i, b, e) for (intmax_t i = (b), i##_limit = (e); i <= i##_limit; ++i)
#define repr(i, b, e) for (intmax_t i = (b), i##_limit = (e); i >= i##_limit; --i)
#define var(Type, ...) Type __VA_ARGS__; input(__VA_ARGS__)
#define let const auto

constexpr size_t    operator""_zu(unsigned long long value) { return value; };
constexpr intmax_t  operator""_jd(unsigned long long value) { return value; };
constexpr uintmax_t operator""_ju(unsigned long long value) { return value; };

constexpr int INF = 0x3f3f3f3f;
constexpr intmax_t LINF = 0x3f3f3f3f3f3f3f3f_jd;

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

inline void input() {}
template <class Head, class... Tail>
inline void input(Head&& head, Tail&&... tail) {
    cin >> head;
    input(forward<Tail>(tail)...);
}

template <class Container, class Value = typename Container::value_type,
            enable_if_t<!is_same<Container, string>::value, nullptr_t> = nullptr>
inline istream& operator>>(istream &is, Container &vs) {
    for (auto &v: vs) is >> v;
    return is;
}

inline void output() { cout << "\n"; }
template <class Head, class... Tail>
inline void output(Head&& head, Tail&&... tail) {
    cout << head;
    if (sizeof...(tail)) cout << " ";
    output(forward<Tail>(tail)...);
}

template <class Container, class Value = typename Container::value_type,
            enable_if_t<!is_same<Container, string>::value, nullptr_t> = nullptr>
inline ostream& operator<<(ostream &os, const Container &vs) {
    static constexpr const char *delim[] = {" ", ""};
    for (auto it = begin(vs); it != end(vs); ++it) {
        os << delim[it == begin(vs)] << *it;
    }
    return os;
}

template <class Iterator>
inline void join(const Iterator &Begin, const Iterator &End, const string &delim = "\n", const string &last = "\n") {
    for (auto it = Begin; it != End; ++it) {
        cout << ((it == Begin) ? "" : delim) << *it;
    }
    cout << last;
}

template <class T>
inline vector<T> makeVector(const T &initValue, size_t sz) {
    return vector<T>(sz, initValue);
}

template <class T, class... Args>
inline auto makeVector(const T &initValue, size_t sz, Args... args) {
    return vector<decltype(makeVector<T>(initValue, args...))>(sz, makeVector<T>(initValue, args...));
}

template <class Func>
class FixPoint : Func {
public:
    explicit constexpr FixPoint(Func&& f) noexcept : Func(forward<Func>(f)) {}

    template <class... Args>
    constexpr decltype(auto) operator()(Args&&... args) const {
        return Func::operator()(*this, std::forward<Args>(args)...);
    }
};

template <class Func>
static inline constexpr decltype(auto) makeFixPoint(Func&& f) noexcept {
    return FixPoint<Func>{forward<Func>(f)};
}

template <class Container>
struct reverse_t {
    Container &c;
    reverse_t(Container &c) : c(c) {}
    auto begin() { return c.rbegin(); }
    auto end() { return c.rend(); }
};

template <class Container>
auto reversed(Container &c) {
    return reverse_t<Container>(c);
}

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

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

template <class T>
inline T diff(const T &a, const T &b) noexcept {
    return a < b ? b - a : a - b;
}

void ioinit() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout << fixed << setprecision(10);
    clog << fixed << setprecision(10);
}
#pragma endregion
// }}} End Header

struct Position {
    pair<int, int> t;
    pair<int, int> k;

    // bool operator<(const Position& rhs) const {
    //     return make_pair(t, k) < make_pair(rhs.t, rhs.k);
    // }
};

signed main() {
    ioinit();

    int W, H;
    while (cin >> W >> H, W) {
        var(int, tx, ty);
        var(int, kx, ky);
        tx--, ty--;
        kx--, ky--;
        auto grid = makeVector<int>(0, H, W);
        input(grid);

        array<int, 4> dy {0, -1, 0, 1};
        array<int, 4> dx {1, 0, -1, 0};
        array<int, 4> rdy {0, 1, 0, -1};
        array<int, 4> rdx {-1, 0, 1, 0};

        const auto able = [&](int y, int x) -> bool {
            return (0 <= y && y < H && 0 <= x && x < W && grid[y][x] == 0);
        };

        const auto start_t = make_pair(ty, tx);
        const auto start_k = make_pair(ky, kx);
        const Position start {start_t, start_k};

        queue<Position> que;
        que.emplace(start);

        auto min_dist = makeVector<int>(INF, H, W, H, W);
        min_dist[ty][tx][ky][kx] = 0;

        int res = INF;

        while (!que.empty()) {
            const Position state = que.front();
            que.pop();
            const int cur_dist = min_dist[state.t.first][state.t.second][state.k.first][state.k.second];
            if (cur_dist >= 100) continue;
            if (state.t == state.k) {
                chmin(res, cur_dist);
                continue;
            }
            rep(dir, 0, 4) {
                const int new_ty = state.t.first + dy[dir];
                const int new_tx = state.t.second + dx[dir];
                const int new_ky = state.k.first + rdy[dir];
                const int new_kx = state.k.second + rdx[dir];
                if (!able(new_ty, new_tx) && !able(new_ky, new_kx)) continue;
                const auto new_t = (able(new_ty, new_tx) ? make_pair(new_ty, new_tx) : make_pair(state.t.first, state.t.second));
                const auto new_k = (able(new_ky, new_kx) ? make_pair(new_ky, new_kx) : make_pair(state.k.first, state.k.second));
                const Position new_state {new_t, new_k};
                const int new_dist = cur_dist + 1;
                if (chmin(min_dist[new_t.first][new_t.second][new_k.first][new_k.second], new_dist)) {
                    que.emplace(new_state);
                }
            }
        }

        if (res == INF) {
            output("NA");
        } else {
            output(res);
        }
    }

    return 0;
}
accuracy: 1
time_ms: 2480
memory_kb: 32360
final_rank: 15

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

using namespace std;

class Position {
public:
	int tx, ty, kx, ky;
	int cnt;

	Position() {
		tx = ty = kx = ky = cnt = 0;
	}

	Position(int x1, int y1, int x2, int y2) : tx(x1), ty(y1), kx(x2), ky(y2) {
		cnt = 0;
	}
};

int W, H, Ans;
int MapData[50][50];
int Dx[4] = { 1,0,-1,0 };
int Dy[4] = { 0,1,0,-1 };
bool Visited[50][50][50][50];

bool solve(int x1, int y1, int x2, int y2) {
	int curTx, curTy, curKx, curKy, nextTx, nextTy, nextKx, nextKy;
	queue<Position> positionList;
	Position curPos, next;

	memset(Visited, false, sizeof(Visited));
	positionList.push(Position(x1, y1, x2, y2));
	while (!positionList.empty()) {
		curPos = positionList.front();
		positionList.pop();

		if (curPos.cnt == 100) {
			return false;
		}
		curTx = curPos.tx;
		curTy = curPos.ty;
		curKx = curPos.kx;
		curKy = curPos.ky;
		if (curTx == curKx && curTy == curKy) {
			Ans = curPos.cnt;
			return true;
		}
		if (Visited[curTx][curTy][curKx][curKy]) {
			continue;
		}
		Visited[curTx][curTy][curKx][curKy] = true;
		next.cnt = curPos.cnt + 1;

		for (int i = 0; i < 4; ++i) {
			nextTx = curTx + Dx[i];
			nextTy = curTy + Dy[i];
			nextKx = curKx - Dx[i];
			nextKy = curKy - Dy[i];
			if (nextTx < 0 || nextTx > W - 1 || nextTy < 0 || nextTy > H - 1 || MapData[nextTy][nextTx] == 1) {
				next.tx = curTx;
				next.ty = curTy;
			}
			else {
				next.tx = nextTx;
				next.ty = nextTy;
			}

			if (nextKx < 0 || nextKx > W - 1 || nextKy < 0 || nextKy > H - 1 || MapData[nextKy][nextKx] == 1) {
				next.kx = curKx;
				next.ky = curKy;
			}
			else {
				next.kx = nextKx;
				next.ky = nextKy;
			}
			positionList.push(next);
		}
	}

	return false;
}

int main() {
	int x1, y1, x2, y2;

	while (cin >> W >> H, W) {
		cin >> x1 >> y1 >> x2 >> y2;
		for (int i = 0; i < H; ++i) {
			for (int j = 0; j < W; ++j) {
				cin >> MapData[i][j];
			}
		}
		if (solve(--x1, --y1, --x2, --y2)) {
			cout << Ans << endl;
		}
		else {
			cout << "NA" << endl;
		}
	}

	return 0;
}
accuracy: 1
time_ms: 100
memory_kb: 10304
final_rank: 1

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using P = pair<int, int>;

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

const int INF = 1001001001;

int w, h;
bool grid[55][55];
int ti[55][55][55][55];
int dx[4] = { 0, 0, -1, 1 }, dy[4] = { -1, 1, 0, 0 };

bool f(int y, int x) {
    if (0 <= y && y < h && 0 <= x && x < w && !grid[y][x]) return true;
    return false;
}

int main() {
    while (cin >> w >> h && !(w == 0 && h == 0)) {
        int tx, ty, kx, ky;
        cin >> tx >> ty >> kx >> ky;
        tx--; ty--; kx--; ky--;
        for (int i = 0; i < h; i++) {
            for (int j = 0; j < w; j++) {
                cin >> grid[i][j];
            }
        }
        for (int i = 0; i < 55; i++) {
            for (int j = 0; j < 55; j++) {
                for (int k = 0; k < 55; k++) {
                    for (int l = 0; l < 55; l++) {
                        ti[i][j][k][l] = INF;
                    }
                }
            }
        }
        queue<T> que;
        que.push(T(ty, tx, ky, kx));
        ti[ty][tx][ky][kx] = 0;
        int gy, gx;
        bool flag = false;
        while (!flag && que.size()) {
            T t = que.front(); que.pop();
            int cty = get<0>(t), ctx = get<1>(t);
            int cky = get<2>(t), ckx = get<3>(t);
            for (int i = 0; i < 4; i++) {
                int nty = cty + dy[i], ntx = ctx + dx[i];
                if (!f(nty, ntx)) nty = cty, ntx = ctx;
                int nky = cky - dy[i], nkx = ckx - dx[i];
                if (!f(nky, nkx)) nky = cky, nkx = ckx;
                if (ti[nty][ntx][nky][nkx] <= ti[cty][ctx][cky][ckx] + 1) continue;
                ti[nty][ntx][nky][nkx] = ti[cty][ctx][cky][ckx] + 1;
                if (nty == nky && ntx == nkx) {
                    gy = nty, gx = ntx;
                    flag = true;
                    break;
                }
                que.push(T(nty, ntx, nky, nkx));
            }
        }
        int ans = ti[gy][gx][gy][gx];
        if (ans < 100) cout << ans << endl;
        else cout << "NA" << endl;
    }
}
accuracy: 1
time_ms: 450
memory_kb: 38956
final_rank: 6

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

struct coor {
    int x, y;
    coor(const int& y_ = 0, const int& x_ = 0) : y(y_), x(x_) {}
    bool operator==(coor& a) { return x == a.x && y == a.y;}
    bool in(int& H, int&W){
        return 0 <= y && y < H && 0 <= x && x < W; 
    }
};

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

void ClearDist(){
    #define rep(i, N) for(int i = 0; i < N; i++)
    
    const int N = 51;
    rep(a,N)rep(b,N)rep(c,N)rep(d,N) dist[a][b][c][d] = -1;
}

int solve(int W, int H){
    int tx, ty;
    int kx, ky;
    cin >> tx >> ty; tx--, ty--;
    cin >> kx >> ky; kx--, ky--;
    vector<vector<int>> grid(H, vector<int>(W));
    for(int h = 0; h < H; h++){
        for(int w = 0; w < W; w++){
            cin >> grid[h][w];
        }
    }
    
    ClearDist();
    dist[ty][tx][ky][kx] = 0;
    coor taka = coor(ty, tx);
    coor kazu = coor(ky, kx);
    int ans = (taka == kazu ? 0 : 100);
    queue<pair<coor, coor>> que;
    que.push({taka, kazu});
    
    while(!que.empty()){
        tie(taka, kazu) = que.front();
        que.pop();

        for(int i = 0; i < 4; i++){
            coor n_taka = coor(taka.y + dy[i], taka.x + dx[i]);
            coor n_kazu = coor(kazu.y - dy[i], kazu.x - dx[i]);
            
            if(!n_taka.in(H, W) && !n_kazu.in(H, W)) continue;

            if(!n_taka.in(H, W) || grid[n_taka.y][n_taka.x] == 1) n_taka = taka;
            if(!n_kazu.in(H, W) || grid[n_kazu.y][n_kazu.x] == 1) n_kazu = kazu;
            if(n_taka == taka && n_kazu == kazu) continue;

            int& nxt = dist[n_taka.y][n_taka.x][n_kazu.y][n_kazu.x];
            if(nxt != -1) continue;

            nxt = dist[taka.y][taka.x][kazu.y][kazu.x] + 1;
            if(n_taka == n_kazu) ans = min(ans, nxt);
            if(nxt < 100) que.push({n_taka, n_kazu});
        }
        
    }
    
    return ans;
}

int main(){
    int W, H;
    while(cin >> W >> H, W != 0){
        int ans = solve(W, H);
        if(ans >= 100) cout << "NA" << endl;
        else cout << ans << endl;
    }
}
accuracy: 1
time_ms: 2570
memory_kb: 30232
final_rank: 14