See the problem statement here: [http://codeforces.com/contest/921/problem/01](//codeforces.com/contest/921/problem/01).
none
none
n, m = map(int, input().split())
grid = []
for _ in range(n):
    grid.append(list(input()))

x, y = 0, 0
for i in range(n):
    for j in range(m):
        if grid[i][j] == 'A':
            x, y = i, j
            break

visited = [[False for _ in range(m)] for _ in range(n)]
visited[x][y] = True

queue = [(x, y, 1)]

directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]

while queue:
    x, y, steps = queue.pop(0)
    for dx, dy in directions:
        new_x, new_y = x + dx, y + dy
        if new_x < 0 or new_x >= n or new_y < 0 or new_y >= m:
            continue
        if visited[new_x][new_y]:
            continue
        if grid[new_x][new_y] == 'B':
            print(steps)
            exit()
        if grid[new_x][new_y] == '.':
            visited[new_x][new_y] = True
            queue.append((new_x, new_y, steps + 1))

print(-1)