//princess
import java.util.Scanner;
class Solution {
static int A[][];
static int qx[] = new int[1000000];
static int qy[] = new int[1000000];
static int S[] = new int[1000000];
static int l, r;
public static void main(String args[]) throws Exception {
//System.setIn(new FileInputStream("input.txt"));
Scanner sc = new Scanner(System.in);
int testCase = sc.nextInt();
for (int t = 1; t <= testCase; t++) {
int n = sc.nextInt();
A = new int[n + 2][n + 2];
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < A.length; j++) {
if (i > 0 && j > 0 && i < (A.length - 1) && j < (A.length - 1)) {
A[i][j] = sc.nextInt();
} else
A[i][j] = 0;
}
}
l = -1;
r = -1;
int[] Dx = { -1, 1, 0, 0 };
int[] Dy = { 0, 0, -1, 1 };
push(1, 1, 1);
int[][] T = new int[n + 2][n + 2];
T[1][1] = 1;
int s = 0;
int k = 0;
int vtx = 0, vty = 0;
while (l != r) {
int x = qx[l + 1];
int y = qy[l + 1];
s = S[l + 1];
pop();
for (int i = 0; i < Dx.length; i++) {
int x1 = x + Dx[i];
int y1 = y + Dy[i];
if (A[x1][y1] == 1 && (T[x1][y1] == 0)) {
T[x1][y1] = s + 1;
push(x1, y1, s + 1);
}
if (A[x1][y1] == 2) {
T[x1][y1] = s;
vtx = x1;
vty = y1;
k = 1;
break;
}
}
if (k == 1)
break;
}
if(k == 0) System.out.println(-1);
else {
for (int i = 0; i < T.length; i++) {
for (int j = 0; j < T.length; j++) {
if (i != vtx || j != vty)
T[i][j] = 0;
}
}
l = -1; r = -1; k = 0;
push(vtx, vty, s);
while (l != r) {
int x = qx[l + 1];
int y = qy[l + 1];
s = S[l + 1];
pop();
for (int i = 0; i < Dx.length; i++) {
int x1 = x + Dx[i];
int y1 = y + Dy[i];
if (A[x1][y1] == 1 && (T[x1][y1] == 0)) {
T[x1][y1] = s + 1;
push(x1, y1, s + 1);
if (x1 == A.length - 2 && y1 == A.length - 2) {
k = 1;
System.out.println(s + 1);
break;
}
}
if (k == 1)
break;
}
if (k == 1)
break;
}
if (k == 0)
System.out.println(-1);
}
}
}
static void push(int x, int y, int s) {
qx[++r] = x;
qy[r] = y;
S[r] = s;
}
static void pop() {
l++;
}
}