#include <iostream>
#include <fstream>
#include <queue>
#include <string>
using namespace std;
typedef pair<int, int> PII;

ifstream fin("DATA3.txt");
ofstream fout("OUT3.txt");

// n w s e
int mX[4] = {-1, 0, 1, 0};
int mY[4] = {0, -1, 0, 1};

int dist[50][50];
char map[50][50];
bool been[50][50];

int wX, wY;

string s;

void findit(int a)
{
	for (int x=0; x<10; x++)
		for (int y=0; y<19; y++)
			if (map[x][y]-'A' == a)
			{
				wX = x;
				wY = y;
				return;
			}
}

int getdist(int a, int b)
{
	int ans = 0;
	queue<PII> q; // position
	queue<int> q2; // dist

	findit(a);
	q.push(PII(wX, wY)); // dist, x, y
	q2.push(0);

	memset(been, false, sizeof been);
	been[wX][wY] = true;
	while (!q.empty())
	{
		PII t = q.front();
		q.pop();

		int d = q2.front();
		q2.pop();

		if (t.first < 0 || t.first > 9 || t.second < 0 || t.second >= 19)
			continue;

		if (map[t.first][t.second] == '#')
			continue;

		been[t.first][t.second] = true;

		if (map[t.first][t.second]-'A' == b)
			return d;

		for (int y=0; y<4; y++)
			if (!been[t.first+mX[y]][t.second+mY[y]])
			{
				q.push(PII(t.first+mX[y], t.second+mY[y]));
				q2.push(d+1);
			}
	}

	return 0;
}

void process()
{
	int x, y;
	memset(dist, 0, sizeof dist);
	for (x=0; x<12; x++)
		for (y=0; y<12; y++)
			dist[x][y] = getdist(x, y);
}

void work()
{
	int ans = 0;
	for (int x=0; x<s.length()-1; x++)
		ans += dist[s[x]-'A'][s[x+1]-'A'];

	fout << ans << endl;
}

int main()
{
	int x, y;
	// size is 10 by 19
	for (x=0; x<10; x++)
		for (y=0; y<19; y++)
			fin >> map[x][y];

	process();
	for (int t=5; t--;)
	{
		fin >> s;
		work();
	}

	return 0;
}
