Manhattan Distance

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值