Formula
dis(i,j)=|xi-xj|+|yi-yj|
E.G.
Input
The input consists of at most 100 datasets, each in the following format.
h w
r1
…
rh
s
The two integers h and w in the first line are the height and the width of the OSK, respectively. They are separated by aspace, and satisfy 1 ≤ h ≤ 50 and 1 ≤ w ≤ 50.
Each of the next h lines gives a row of the OSK. The i-th row, ri is a string of length w. The characters in the stringcorresponds to the characters in the cells of the i-th row of the OSK or an underscore (‘_’) indicating an empty cell, fromleft to right.
The given OSK satisfies the conditions stated above.
The next line is a string s to be input. Its length is between 1 and 1000, inclusive. All the characters in s appear in the givenOSK. Note that s does not contain underscores.
The end of the input is indicated by a line containing two zeros.
Output
For each dataset, output a single line containing an integer indicating the minimum number of button presses required toinput the given string with the given OSK.
Sample Input
3 9
ABCDEFGHI
JKLMNOPQR
STUVWXYZ_
ICPC
5 11
___________
____A______
________M__
___________
_C_________
ACM
4 21
1_2_3_4_5_6_7_8_9_0_-
QqWwEeRrTtYyUuIiOoPp@
AaSsDdFfGgHhJjKkLl;_:
ZzXxCcVvBbNnMm,_._/__
ICPC2019,AsiaYokohamaRegional,QualificationRound
0 0
Sample Output
28
23
493
Code
#define _CRT_SECURE_NO_WARNINGS
#include<bits/stdc++.h>
using namespace std;
int h, w;
const int H = 55;
const int W = 55;
char arr1[H][W];
char arr2[1005];
int x[1005], y[1005];
int main() {
while (~(scanf("%d %d", &h, &w))) {
if (h == 0 && w == 0)break;
memset(arr1, 0, sizeof(arr1));
memset(arr2, 0, sizeof(arr2));
memset(x, 0, sizeof(x));
memset(y, 0, sizeof(y));
for (int i = 0; i < h; i++) {
scanf("%s", arr1[i]);
for (int j = 0; j < w; j++) {
int val = int(arr1[i][j]);
x[val] = i;
y[val] = j;
}
}
scanf("%s", arr2);
int ans = 0, px = 0, py = 0;
for (int i = 0; i < strlen(arr2); i++) {
int val = (int)arr2[i];
ans += abs(px - x[val]) + abs(py - y[val]) + 1;
px = x[val];
py = y[val];
}
cout << ans << endl;
}
return 0;
}