#define _CRT_SECURE_NO_WARNINGS
#include <cstdio>
#include <vector>
#include <queue>
#include <cstring>
#include <algorithm>
using namespace std;
const int inf = 1e9;
int dist[1 << 11][55][55], ad[55][55], n, x, y, ex, ey;
bool v[1 << 11][55][55];
int dx[] = { -1, 1, 0, 0 };
int dy[] = { 0, 0, -1, 1 };
struct ii {
int x, y, m;
ii(int a, int b, int c) {
x = a, y = b, m = c;
}
};
bool valid(int nx, int ny) {
return nx >= 0 && ny >= 0 && nx < n && ny < n;
}
int bfs(int x, int y) {
int ans = inf, mm = ad[x][y];
queue <ii> q; q.push(ii(x, y, (1 << mm)));
dist[(1 << mm)][x][y] = 1;
while (!q.empty()) {
ii curr = q.front(); q.pop();
int X = curr.x, Y = curr.y, ma = curr.m;
if (X == ex && Y == ey)
ans = min(ans, dist[ma][X][Y]);
if (v[ma][X][Y]) continue;
v[ma][X][Y] = true;
for (int i = 0; i < 4; i++) {
int nx = X + dx[i], ny = Y + dy[i];
if (valid(nx, ny)) {
int mask = ma, j = ad[nx][ny];
if (!(mask & (1 << j))) {
mask |= (1 << j);
dist[mask][nx][ny] = dist[ma][X][Y] + 1;
q.push(ii(nx, ny, mask));
} else {
dist[mask][nx][ny] = dist[ma][X][Y];
q.push(ii(nx, ny, mask));
}
}
}
}
//if (ans == 0) ans = 1;
return ans;
}
#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, false, sizeof v);
printf("%d\n", bfs(x, y));
}
}
I2RlZmluZSBfQ1JUX1NFQ1VSRV9OT19XQVJOSU5HUwojaW5jbHVkZSA8Y3N0ZGlvPgojaW5jb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