/*
  [BAPC'07] ESCAPE
  by: Jan Kuipers
*/

#include <iostream>
#include <queue>
#include <string>

using namespace std;

const int dy[4] = { 1, 0,-1, 0 };
const int dx[4] = { 0,-1, 0, 1 };

int main () {

  int runs;
  cin>>runs;
  while (runs--) {

    int Y,X;
    cin>>Y>>X;
    vector<string> m(Y);
    for (int i=0; i<Y; i++) cin>>m[i];

    int sy=-1, sx=-1;
    for (int y=0; y<Y; y++)
      for (int x=0; x<X; x++)
	if (m[y][x]=='@') sy=y, sx=x;

    vector<int> dist(Y*X*4,-1);
    
    queue<int> q;
    for (int d=0; d<4; d++) {
      q.push(sy);
      q.push(sx);
      q.push(d);
      q.push(0);
    }

    int solved=0;
    
    while (!q.empty()) {

      int y=q.front(); q.pop();
      int x=q.front(); q.pop();
      int d=q.front(); q.pop();
      int D=q.front(); q.pop();
      int idx=4*(y*X+x)+d;
      
      if (dist[idx]!=-1) continue;
      dist[idx]=D;

      if (x==0||y==0||x==X-1||y==Y-1) {
	cout<<D<<endl;
	solved=1;
	break;
      }
      
      int turn=0;
      
      for (int i=0; i<2; i++) {
	int nd=(d+2*i+1)%4;
	int ny=y+dy[nd];
	int nx=x+dx[nd];
	if (ny<0||ny>=Y||nx<0||nx>=X) continue;
	if (m[ny][nx]=='#') continue;

	q.push(ny);
	q.push(nx);
	q.push(nd);
	q.push(D+1);
	turn=1;
      }
      
      if (!turn) {
	int ny=y+dy[d];
	int nx=x+dx[d];
	if (ny>=0&&ny<Y&&nx>=0&&nx<X&&m[ny][nx]!='#') {
	  q.push(ny);
	  q.push(nx);
	  q.push(d);
	  q.push(D+1);
	}
      }
    }

    if (!solved) cout<<-1<<endl;
  }
  
  return 0;
}
