/*
ID: raknarf1
PROG: dwite5
LANG: C++
 */

#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <ctime>

using namespace std;

int best = 10000000, n;
char g[26][5][5];
int di[] = {-1, 0, 1, 0, 0};
int dj[] = {0, 1, 0, -1, 0};
bool found = false;

void dfs(int k, int i, int j, int step)
{
    if (step>=best || found) return;
    if (g[k][i][j]=='B')
    {
	best = step;
	found = true;
	return;
    }

    for (int x=0; x<5; x++)
	try
	{
            int ni = i+di[x];
            int nj = j+dj[x];
            int nk = k+1;

            if (g[nk][ni][nj]=='B' || g[nk][ni][nj]=='.')
                dfs(nk, ni, nj, step+1);

	}
    catch (char *str) { };

    return;
}

int main()
{
  //  clock_t start_p = clock();

    ifstream f("DATA5.txt");
    ofstream out("OUT5.txt");

    string line = "";
    for (int y=0; y<5; y++)
    {
	best = 10000000;
	found = false;
        f >> n;
			
    for (int k=0; k<26; k++)
        for (int i=0; i<5; i++)
            for (int j=0; j<5; j++)
                g[i][j][k] = '#';

			
    for (int k=0; k<n; k++)
	for (int i=0; i<5; i++)
        {
            f >> line;
            for (int j=0; j<5; j++)
                g[k][i][j] = line[j];
        }


	for (int k=0; k<n; k++)
            for (int i=0; i<5; i++)
		for (int j=0; j<5; j++)
		{
                    if (g[k][i][j]=='A')
                    {
                        dfs(k, i, j, 0);
                        goto end;
                    }
                }

        end:
	out << best << endl;
    }
	
   // cout << "Time Elapsed: " << (clock() - start_p) / (double) CLOCKS_PER_SEC << endl;
    return 0;
}

