#include <iostream>
#include <vector>
#include <string>
using namespace std;

const int N = 80;   /* size limit */

int H, W, sr, sc;
bool blocked[N][N];
const int dr[4] = {  0, +1,  0, -1 };
const int dc[4] = { +1,  0, -1,  0 };

int solve()
{
    bool visited[4][N][N] = { };
    vector<int> queue, next_queue;
    queue.push_back(N*N*0 + N*sr + sc);
    queue.push_back(N*N*1 + N*sr + sc);
    queue.push_back(N*N*2 + N*sr + sc);
    queue.push_back(N*N*3 + N*sr + sc);
    int steps = 0;
    while(!queue.empty())
    {
        int cur = queue.back(), dir = cur/N/N, row = (cur/N)%N, col = cur%N;
        queue.pop_back();

        if(row == 0 || row == H - 1 || col == 0 || col == W - 1)
            return steps;

        int dirs[2], ndirs = 0;
        if(!blocked[row + dr[(dir + 1)%4]][col + dc[(dir + 1)%4]])
            dirs[ndirs++] = (dir + 1)%4;
        if(!blocked[row + dr[(dir + 3)%4]][col + dc[(dir + 3)%4]])
            dirs[ndirs++] = (dir + 3)%4;
        if(ndirs == 0 && !blocked[row + dr[dir]][col + dc[dir]])
            dirs[ndirs++] = dir;

        for(int d = 0; d < ndirs; ++d)
        {
            int nd = dirs[d], nr = row + dr[nd], nc = col + dc[nd];
            if(!visited[nd][nr][nc])
            {
                visited[nd][nr][nc] = true;
                next_queue.push_back(N*N*nd + N*nr + nc);
            }
        }

        if(queue.empty())
        {
            ++steps;
            queue.swap(next_queue);
        }
    }
    return -1;
}

int main()
{
    int cases;
    cin >> cases;
    while(cases--)
    {
        cin >> H >> W;
        string line;
        for(int r = 0; r < H; ++r)
        {
            cin >> line;
            for(int c = 0; c < W; ++c)
            {
                blocked[r][c] = (line[c] == '#');
                if(line[c] == '@')
                    sr = r, sc = c;
            }
        }
        cout << solve() << endl;
    }
}
