#include <iostream>
#include <fstream>
#include <algorithm>
#include <queue>

using namespace std;

struct Point{
    int r, c, time;

};

int dr[] = { -1, 0, 1, 0, 0 };
int dc[] = { 0,  1, 0, -1, 0};
int n;

bool inBounds(int r, int c, int time)
{
    return (r >= 0 && r < 5 && c >= 0 && c < 5 && time < n);
}

int main()
{
    ifstream fin("data5.txt");
    ofstream fout("out5.txt");
    int i , j, k, l;

    for (i = 0; i < 5; ++i)
    {
        Point start;
        Point end[50];
        fin >> n;
        char grid[10][10][50];

        for (j = 0; j < n; ++j)
        {
            for (k = 0; k < 5; ++k)
            {
                for (l = 0; l < 5; ++l)
                {
                    fin >> grid[k][l][j];
                    if (grid[k][l][j] == 'A' && j == 0)
                    {
                        start.r = k;
                        start.c = l;
                    }
                    if (grid[k][l][j] == 'B')
                    {
                        end[j].r = k;
                        end[j].c = l;
                    }
                }
            }
        }
        start.time = 0;
        queue <Point> Q;
        Q.push(start);
        int dist[10][10][50];
        memset(dist,-1,sizeof(dist));
        dist[start.r][start.c][0] = 0;
        int solu = 1000000;
        while (!Q.empty())
        {
            Point cur = Q.front();
            Q.pop();
            if (grid[cur.r][cur.c][cur.time] == 'B')
            {
                if (dist[cur.r][cur.c][cur.time] < solu)
                    solu = dist[cur.r][cur.c][cur.time] ;
            }
            for (j = 0; j < 5; ++j)
            {
                Point next;
                next.r = cur.r + dr[j];
                next.c = cur.c + dc[j];
                next.time = cur.time +1;
                if (inBounds(next.r,next.c, next.time) && dist[next.r][next.c][next.time] == -1
                    && grid[next.r][next.c][next.time] != '#')
                {
                    dist[next.r][next.c][next.time] = dist[cur.r][cur.c][cur.time] + 1;
                    //if (j == 4) dist[next.r][next.c][next.time]--;
                    Q.push(next);
                }
            }
        }

        fout << solu << endl;





    }

    return 0;
}

