Enterprising Escape
The Enterprise is surrounded by Klingons! Find the escape route that has the quickest exit time, and print that time.
Input is a rectangular grid; each grid square either has the Enterprise or some class of a Klingon warship. Associated with each class of Klingon warship is a time that it takes for the Enterprise to defeat that Klingon. To escape, the Enterprise must defeat each Klingon on some path to the perimeter. Squares are connected by their edges, not by corners (thus, four neighbors).
Input
The first line will contain the number of cases t (2 ≤ t ≤ 100). Each case will start with line containing three numbers k, w and h. The value for k (1 ≤ k ≤ 25) is the number of different Klingon classes. The value for w (2 ≤ w ≤ 1000) is the width of the grid. The value for h (1 ≤ w ≤ 1000) is the height of the grid.
Following that will be k lines. Each will consist of a capital letter used to label the class of Klingon ships followed by the duration required to defeat that class of Klingon. The label will not be "E". The duration is in minutes and will be between 0 and 100000 inclusive. Each label will be distinct.
Following that will be h lines. Each will consist of w capital letters (with no spaces between them). There will be exactly one "E" across all h lines, denoting the location of the Enterprise; all other capital letters will be one of the k labels given above, denoting the class of Klingon warship in the square.
Output
Print a single integer - the time required for the Enterprise to escape.