#define _CRT_SECURE_NO_WARNINGS
#include <cstdio>
#include <vector>
#include <queue>
#include <cstring>
#include <algorithm>
using namespace std;
const int inf = 1e9;
int dist[55][55], ad[55][55], n, x, y, ex, ey;
int v[55][55];
int dx[] = { -1, 1, 0, 0 };
int dy[] = { 0, 0, -1, 1 };
struct ii {
int x, y;
ii(int a, int b) {
x = a, y = b;
}
};
bool valid(int nx, int ny) {
return nx >= 0 && ny >= 0 && nx < n && ny < n;
}
bool checkBit(int mask, int bit) {
return (mask & (1 << bit));
}
bool bfs(int x, int y, int mask) {
if (!checkBit(mask, ad[x][y])) {
return false;
}
queue <ii> q; q.push(ii(x, y));
v[x][y] = mask;
while (!q.empty()) {
ii curr = q.front(); q.pop();
int X = curr.x, Y = curr.y;
if (X == ex && Y == ey)
return true;
for (int i = 0; i < 4; i++) {
int nx = X + dx[i], ny = Y + dy[i];
if (valid(nx, ny) && checkBit(mask, ad[nx][ny])) {
if (v[nx][ny] != mask) {
v[nx][ny] = mask;
q.push(ii(nx, ny));
}
}
}
}
return false;
}
#define gc getchar_unlocked
void s(int &x) {
register int c = gc();
x = 0;
for (; (c<48 || c>57); c = gc());
for (; c > 47 && c < 58; c = gc()) { x = (x << 1) + (x << 3) + c - 48; }
}
int main(void) {
//freopen("in.txt", "r", stdin);
int t; s(t);
while (t--) {
s(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
s(ad[i][j]);
}
}
s(x), s(y), s(ex), s(ey);
memset(dist, 0x3f, sizeof dist);
memset(v, (1 << 11), sizeof v);
int ans = inf;
for (int mask = 1, lim = (1 << 10); mask < lim; ++mask) {
if (bfs(x, y, mask)) {
int bit_count = 0;
for (int bit = 0; bit < 10; ++bit) {
if (checkBit(mask, bit)) {
++bit_count;
}
}
ans = (ans > bit_count? bit_count: ans);
}
}
printf("%d\n", ans);
}
}
I2RlZmluZSBfQ1JUX1NFQ1VSRV9OT19XQVJOSU5HUwojaW5jbHVkZSA8Y3N0ZGlvPgojaW5jbHVk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