#include #include #include #include #include #include #include #include #include #include using namespace std; const int maxn = 510; int T; int n, x, y; int M[maxn][maxn] = {0}; int cnt[4] = {0}; #define P pair #define mp make_pair #define fi first #define se second struct node { int i, j, v; node(int _i = 0, int _j = 0, int _v = 0) { i = _i, j = _j, v = _v; } } ; vector V; bool cmp(const node& A, const node& B) { return (A.v > B.v); } inline int Abs(int x) { return (x < 0 ? -x : x); } inline bool IN(int i, int j) { return (i >= 1 && i <= n && j >= 1 && j <= n); } int main() { ios::sync_with_stdio(0); cin >> T; while (T--) { cin >> n >> x >> y; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= n; ++j) { cin >> M[i][j]; } } int ans = 0x3f3f3f3f; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= n; ++j) { V.clear(); cnt[1] = cnt[2] = cnt[3] = 0; int ret = 0; int food = 0; int dx = Abs(x - i), dy = Abs(y - j); int d = dx / 2; if (dx & 1) { d++; if (dy != 0) dy--; } d += dy / 2; if (dy & 1) d++; ret += d; cnt[M[i][j]]++; for (int di = -3; di <= 3; ++di) { for (int dj = -3; dj <= 3; ++dj) { if (di == 0 && dj == 0) continue; if (Abs(di) + Abs(dj) <= 3) { if (IN(i + di, j + dj)) { V.push_back(node(i + di, j + dj, M[i + di][j + dj])); } } } } sort(V.begin(), V.end(), cmp); int pt = 0, sz = V.size(); for (int tot = 1; tot <= 8; ++tot) { int deta = 0; for (int k = 1; k <= 3; ++k) deta += cnt[k] * k; int days = (8 * tot * tot - food) / deta; if ((8 * tot * tot - food) % deta != 0) ++days; if (8 * tot * tot <= food) days = 0; food += deta * days; ret += days; int curmx = 1; if (pt != sz) { cnt[V[pt].v]++; pt++; } } ans = min(ans, ret); } } cout << ans << endl; } return 0; }