#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
#define MAXN 1000
typedef pair<int,int> P;
char map[MAXN][MAXN];
bool visited[MAXN][MAXN];
int N,M;
queue<P> q,fire;
int dx[] = {0,0,1,-1};
int dy[] = {1,-1,0,0};
int bfs(){
int cnt = 0;
while (!q.empty()){
int q_size = fire.size();
while (q_size--){
int x = fire.front().first;
int y = fire.front().second;
fire.pop();
for (int k = 0; k<4; k++){
int nx = x+dx[k];
int ny = y + dy[k];
if (nx < 0 || ny < 0||nx>=N || ny>=M) continue;
if (map[nx][ny]=='.'){
map[nx][ny] = '*';
fire.push({nx,ny});
}
}
}
q_size = q.size();
while (q_size--){
int x = q.front().first;
int y = q.front().second;
q.pop();
if (x == 0 || y == 0 || x == N-1 || y == M - 1) return cnt+1;
for (int k = 0; k < 4; k++){
int nx = x + dx[k];
int ny = y + dy[k];
if (nx < 0 || ny < 0 || nx>=N || ny>=M) continue;
if (map[nx][ny] =='.' && !visited[nx][ny]){
visited[nx][ny] = true;
q.push({nx,ny});
}
}
}
cnt++;
}
return -1;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int t;
cin >> t;
while (t--){
memset(visited,false,sizeof(visited));
while (!q.empty()) q.pop();
while (!fire.empty()) fire.pop();
cin >> M >> N;
for (int i = 0; i < N; i++){
cin >> map[i];
for (int j= 0;j<M; j++){
if (map[i][j] == '*'){
fire.push({i,j});
}
else if (map[i][j]=='@'){
q.push({i,j});
map[i][j] ='.';
visited[i][j] = true;
}
}
}
int ans = bfs();
if (ans ==-1) cout << "IMPOSSIBLE"<<"\n";
else cout << ans <<"\n";
}
return 0;
}