#include <iostream>
#include <fstream>
#include <string>

using namespace std;

ifstream fin("DATA5.txt");
ofstream fout("OUT5.txt");

char map[5][5][5];
int dist[5][5][5];

struct xyz {
	int x, y, z;
};

xyz start, end;
int size;

void readgrid() {
	string buff;
	for (int x = 0; x < size; x++) {
		for (int y = 0; y < size; y++) {
			getline(fin, buff);
			for (int z = 0; z < size; z++) {
				map[x][y][z] = buff[z];
				if (buff[z] == 'A') {
					start.x = x;
					start.y = y;
					start.z = z;
				}
				if (buff[z] == 'B') {
					end.x = x;
					end.y = y;
					end.z = z;
				}
				dist[x][y][z] = 9999;
			}
		}
	}
}

int xmoves[] = {1, -1, 0, 0, 0, 0};
int ymoves[] = {0, 0, 1, -1, 0, 0};
int zmoves[] = {0, 0, 0, 0, 1, -1};

void filldist(int x, int y, int z, int newdist) {
	if (map[x][y][z] != '#' && dist[x][y][z] > newdist) {
		dist[x][y][z] = newdist;
		for (int i = 0; i < 6; i++) {
			int newx = x + xmoves[i];
			int newy = y + ymoves[i];
			int newz = z + zmoves[i];
			if (newx >= 0 && newx < size && newy >= 0 && newy < size && newz >= 0 && newz < size)
				filldist(newx, newy, newz, newdist + 1);
		}
	}
}

int main() {
	string blackhole;
	for (int i = 0; i < 5; i++) {
		fin >> size;
		getline(fin, blackhole);
		readgrid();

		filldist(start.x, start.y, start.z, 0);

		fout << dist[end.x][end.y][end.z] << endl;
	}
}

