#include <cstdio>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;

#define PB push_back
#define SZ(v) ((int)(v).size())
#define MP make_pair
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) FOR(i,0,n)
#define FORE(i,a,b) for(int i=(a);i<=(b);++i)
#define REPE(i,n) FORE(i,0,n)
#define REPSZ(i,v) REP(i,SZ(v))

typedef struct S { int x,y,z; } S;

int h,w;
char g[80][80];

int done[80][80][4];

void run() {
	scanf("%d%d",&h,&w);
	REP(i,h) REP(j,w) scanf(" %c",&g[i][j]);
	
	memset(done,0,sizeof(done));
	queue<S> q;
	int cur=0;
	REP(i,h) REP(j,w) if(g[i][j]=='@') {
		g[i][j]='.';
		REP(k,4) done[i][j][k]=1,q.push((S){i,j,k});
	}
	while(!q.empty()) {
		queue<S> nq;
		while(!q.empty()) {
			int x=q.front().x,y=q.front().y,z=q.front().z; q.pop();
			if(x==0||x==h-1||y==0||y==w-1) { printf("%d\n",cur); return; }
			bool canstraight=true;
			int DX[]={-1,0,+1,0},DY[]={0,+1,0,-1},DZ[]={1,3,0};
			REP(i,3) {
				if(DZ[i]==0&&!canstraight) continue;
				int nz=(z+DZ[i])%4,nx=x+DX[nz],ny=y+DY[nz];
				if(g[nx][ny]!='#') {
					canstraight=false;
					if(!done[nx][ny][nz]) done[nx][ny][nz]=1,nq.push((S){nx,ny,nz});
				}
			}
		}
		q=nq; ++cur;
	}
	printf("-1\n");
}

int main() {
	int n; scanf("%d",&n); FORE(i,1,n) run();
	return 0;
}
	
