#include using namespace std; #ifdef DEBUG #define display(x) cerr << #x << " = " << x << endl; #define eprintf(...) fprintf(stderr, __VA_ARGS__) #else #define display(x) {} #define eprintf(...) do {} while(0) #endif template bool chmin(T &a, const T &b) { return a > b ? a = b, true : false; } template bool chmax(T &a, const T &b) { return a < b ? a = b, true : false; } template ostream& operator << (ostream& out, const vector &v) { int n = v.size(); out << "{"; for(int i = 0; i < n; ++i) { if(i) out << ", "; out << v[i]; } return out << "}"; } template ostream& operator << (ostream& out, const pair &v) { return out << "(" << v.first << ", " << v.second << ")"; } typedef long long LL; typedef pair pii; const int maxN = 500 + 5; int G[maxN][maxN]; int f[4][51][51][51]; int simu(int s, vector cnt) { int man = 1; int per = s, food = 0; int freeman = 0; for(int round = 1; ; ++round) { while(freeman && cnt[3] > 0) --freeman, --cnt[3], per += 3; while(freeman && cnt[2] > 0) --freeman, --cnt[2], per += 2; while(freeman && cnt[1] > 0) --freeman, --cnt[1], per += 1; food += per; while(food >= 8 * man * man) ++man, ++freeman; if(man == 9) return round; } return -1; } void init() { for(int s = 1; s <= 3; ++s) for(int x = 0; x <= 50; ++x) for(int y = 0; y <= 50; ++y) for(int z = 0; z <= 50; ++z) { f[s][x][y][z] = simu(s, {0, x, y, z}); } } void solve() { int n, sx, sy; cin >> n >> sx >> sy; for(int i = 1; i <= n; ++i) for(int j = 1; j <= n; ++j) cin >> G[i][j]; int ans = 1000000000; for(int x = 1; x <= n; ++x) for(int y = 1; y <= n; ++y) { int dist = abs(x - sx) + abs(y - sy); vector cnt = {0, 0, 0, 0}; for(int dx = -3; dx <= 3; ++dx) for(int dy = -3; dy <= 3; ++dy) if(abs(dx) + abs(dy) <= 3 && !(dx == 0 && dy == 0)) if(1 <= x + dx && x + dx <= n && 1 <= y + dy && y + dy <= n) cnt[G[x + dx][y + dy]]++; chmin(ans, (dist + 1) / 2 + f[G[x][y]][cnt[1]][cnt[2]][cnt[3]]); } cout << ans << endl; } int main() { #ifndef LOCAL ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); #endif init(); int T; cin >> T; while(T--) solve(); return 0; }