#include <iostream>
#include <queue>
using namespace std;

#define For(i,a,b) for (int i = a; i < b; i++)

int main()
{
	freopen("DATA3.txt", "r", stdin);
	freopen("OUT3.txt", "w", stdout);

	string grid[11];
	
	For (i, 0, 10)
		cin >> grid[i];
		
	int R = 10, C = grid[0].size();
	
	pair<int,int> loc[26];
	For (i, 0, R)
		For (j, 0, C)
			if (isupper(grid[i][j]))
				loc[grid[i][j]-'A'] = make_pair(i,j);
	
	int dist[10][20][10][20];
	memset(dist, 0x3f, sizeof(dist));
	For (i, 0, R)
		For (j, 0, C)
		if (grid[i][j] != '#')
		{
			int dr[4] = {0,0,1,-1};
			int dc[4] = {1,-1,0,0};
			queue<pair<int,int> > bfs;
			bfs.push(make_pair(i,j));
			dist[i][j][i][j] = 0;
			while (!bfs.empty())
			{
				pair<int,int> x = bfs.front(); bfs.pop();
				int r = x.first, c = x.second;
				int d = dist[i][j][r][c];
				For (k, 0, 4)
				{
					unsigned nr = r + dr[k], nc = c + dc[k];
					if (nr < R && nc < C  && grid[nr][nc] != '#')
						if (dist[i][j][nr][nc] > 10000)
							dist[i][j][nr][nc] = d+1, bfs.push(make_pair(nr,nc));
				}
			}
		}
	
	For (T, 0, 5)
	{
		string s; cin >> s;
		int d = 0;
		char st = s[0];
		For (i, 1, s.size())
		{
			pair<int,int> a = loc[st-'A'];
			pair<int,int> b = loc[s[i]-'A'];
			d += dist[a.first][a.second][b.first][b.second];
			st = s[i];
		}
		cout << d << endl;
	}
	
	//system("pause")
	return 0;
}
