// Arup Guha
// 11/21/2013
// Solution to 2013 Pacific North West Problem E: Enterprising Escape

import java.util.*;

public class e {

	public static int R;
	public static int C;
	public static int[] times;
	public static char[][] grid;

	public static void main(String[] args) {

		Scanner stdin = new Scanner(System.in);
		int numCases = stdin.nextInt();

		// Go through each case.
		for (int loop=0; loop<numCases; loop++) {

			// Read in the data for the case.
			int types = stdin.nextInt();
			C = stdin.nextInt();
			R = stdin.nextInt();
			times = new int[26];
			for (int i=0; i<types; i++) {
				int letter = stdin.next().charAt(0) - 'A';
				times[letter] = stdin.nextInt();
			}
			grid = new char[R][];
			for (int i=0; i<R; i++)
				grid[i] = stdin.next().toCharArray();

			// Output solution.
			System.out.println(solve());
		}
	}

	public static int solve() {

		// Set up BFS.
		int start = findE();
		boolean[] used = new boolean[R*C];
		used[start] = true;

		PriorityQueue<pair> q = new PriorityQueue<pair>();
		q.offer(new pair(start, 0));

		while (q.size() > 0) {

			// Get next item from the queue.
			pair p = q.poll();
			int loc = p.sq;
			int dist = p.dist;

			if (edge(loc)) return dist;

			// Go through next locations.
			ArrayList<Integer> list = getNext(loc);
			for (int i=0; i<list.size(); i++) {

				int next = list.get(i);
				if (!used[next]) {
					q.offer(new pair(next, dist+times[grid[next/C][next%C]-'A']));
					used[next] = true;
				}
			}
		}

		// Should never get here.
		return -1;
	}

	public static int findE() {

		// Go through the grid, looking for E.
		for (int i=0; i<R; i++)
			for (int j=0; j<C; j++)
				if (grid[i][j] == 'E')
					return i*C + j;

		// Should never get here.
		return -1;
	}

	// Get next locations
	public static ArrayList<Integer> getNext(int loc) {
		ArrayList<Integer> ans = new ArrayList<Integer>();

		// Look in all four directions and add the valid ones.
		if (loc/C > 0) ans.add(loc-C);
		if (loc/C < R-1) ans.add(loc+C);
		if (loc%C > 0) ans.add(loc-1);
		if (loc%C < C-1) ans.add(loc+1);
		return ans;
	}

	public static boolean edge(int loc) {
		return loc/C == 0 || loc/C == R-1 || loc%C == 0 || loc%C == C-1;
	}
}

class pair implements Comparable<pair> {

	public int sq;
	public int dist;

	public pair(int square, int distance) {
		sq = square;
		dist = distance;
	}

	public int compareTo(pair other) {
		return this.dist - other.dist;
	}
}