https://www.acmicpc.net/problem/5427!
import sys
from collections import deque
input = sys.stdin.readline
dx = [0, 0, -1, 1]
dy = [1, -1, 0, 0]
def bfs():
while que:
x, y, s = que.popleft()
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0 <= nx < n and 0 <= ny < m:
if visited[nx][ny] == 0 and maps[nx][ny] == '.':
visited[nx][ny] = visited[x][y] + 1
que.append((nx, ny, s))
else:
if s == '@':
return visited[x][y]+1
testCase = int(input())
for _ in range(testCase):
m, n = map(int, input().split())
maps = []
que = deque()
visited = [[0 for _ in range(m)]for _ in range(n)]
for _ in range(n):
maps.append(list(input().rstrip('\n')))
for i in range(n):
for j in range(m):
if maps[i][j] == '@':
que.append((i, j, '@'))
elif maps[i][j] == '*':
que.appendleft((i, j, '*'))
ans = bfs()
if ans:
print(ans)
else:
print("IMPOSSIBLE")