import java.io.*;
import java.util.*;

/** The "P1" class.
  * A brief description of this class
  * @author your name
  * @version date
 */
public class P3
{
    public static char[] [] maze;
    public static boolean[] [] visited;
    static int count = 0;
    public static int search (int r, int c, int m, char t)
    {
count++;
	if (r < 0 || r > 9 || c < 0 || c > 18)
	{
	   // System.out.println (r + " " + c + " " + m);
	    return 9999999;
	}
	if (maze [r] [c] == '#')
	{
	    
	   // System.out.println (r + " " + c + " " + m);
	    return 9999999;
	}
	if (visited [r] [c])
	    return 9999999;
	if (maze [r] [c] == t)
	    return m;
	//System.out.println (r + " " + c + " " + m);
	visited [r] [c] = true;
	int best = 9999999;
	best = Math.min (best, search (r - 1, c, m + 1, t));
	best = Math.min (best, search (r + 1, c, m + 1, t));
	best = Math.min (best, search (r, c - 1, m + 1, t));
	best = Math.min (best, search (r, c + 1, m + 1, t));
	visited [r] [c] = false;
	return best;
    }


    public static void main (String[] args) throws IOException
    {
	BufferedReader in = new BufferedReader (new FileReader ("DATA3.txt"));
	PrintWriter out = new PrintWriter (new FileWriter ("OUT3.txt"));
	maze = new char [10] [19];

	for (int i = 0 ; i < 10 ; i++)
	{
	    maze [i] = in.readLine ().toCharArray ();
	}
	for (int i = 1 ; i <= 5 ; i++)
	{
	    String x = in.readLine ();
	    //if (x.length () == 1)
	    //    out.println (0);
	    //else
	    {
		String text = "ABCDEFGHIJKL";
		int[] startposr = {0, 3, 7, 7, 3, 3, 3, 3, 3, 3, 9, 9};
		int[] startposc = {9, 3, 3, 15, 15, 7, 8, 9, 10, 11, 5, 13};
		int totalDistance = 0;
		for (int q = 0 ; q < x.length () - 1 ; q++)
		{
		    visited = new boolean [10] [19];
		    int r = startposr [text.indexOf (x.charAt (q))];
		    int c = startposc [text.indexOf (x.charAt (q))];                 
		    totalDistance += search (startposr [text.indexOf (x.charAt (q))], startposc [text.indexOf (x.charAt (q))], 0, x.charAt (q + 1));
		}
		out.println (totalDistance);
		
	    }
	}

	in.close ();
	out.close ();

    } // main method
} // P1 class

