Go: package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var scanner = bufio.NewScanner(os.Stdin)

func nextString() string {
	scanner.Scan()
	return scanner.Text()
}

func nextInt() int {
	n, err := strconv.Atoi(nextString())
	if err != nil {
		fmt.Printf("strconv.Atoi failed: %v\n", err)
	}
	return n
}

type Position = []int

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

func main() {
	scanner.Split(bufio.ScanWords)

	for {
		h := nextInt()
		w := nextInt()

		if h == 0 && w == 0 {
			break
		}
		positions := map[string]Position{}
		for i := 0; i < h; i++ {
			row := nextString()
			for j := 0; j < w; j++ {
				pos := []int{i, j}
				positions[row[j:(j+1)]] = pos
			}
		}
		// fmt.Println(positions)

		x := 0
		y := 0
		totalDistance := 0

		queryRow := nextString()
		for i := 0; i < len(queryRow); i++ {
			q := queryRow[i:(i + 1)]

			nextPos := positions[q]
			xNext := nextPos[0]
			yNext := nextPos[1]

			totalDistance += abs(xNext-x) + abs(yNext-y) + 1
			x = xNext
			y = yNext
			// fmt.Println(nextPos, totalDistance)
		}
		fmt.Println(totalDistance)
	}
}

Python: import os,re,sys,operator
from collections import Counter,deque
from operator import itemgetter
from itertools import accumulate,combinations,groupby
from sys import stdin,setrecursionlimit
from copy import deepcopy
import heapq

setrecursionlimit(10**6)
while 1:
    h,w=map(int,stdin.readline().rstrip().split())
    if (h,w)==(0,0):
        break
    a=[stdin.readline().rstrip() for _ in range(h)]
    s=input()
    nx,ny=0,0
    o=0
    cnt=0
    for i in s:
        nh=0
        for j in range(h):
            if i in a[j]:
                o=a[j].index(i)
                cnt+=(abs(nx-o)+abs(ny-nh)+1)
                break
            else:
                nh+=1
        nx,ny=o,nh
    print(cnt)

Python: # -*- coding: utf-8 -*-
"""
スクリーンキーボード
https://onlinejudge.u-aizu.ac.jp/challenges/sources/ICPC/Prelim/1633

"""
import sys


def solve(h, w):
    keyboard = dict()
    for y in range(h):
        for x, ch in enumerate(input()):
            keyboard[ch] = (x, y)

    cx, cy = 0, 0
    ans = 0
    for ch in input():
        nx, ny = keyboard[ch]
        ans += (abs(nx - cx) + abs(ny - cy) + 1)
        cx, cy = nx, ny
    return ans


def main(args):
    while True:
        h, w = map(int, input().split())
        if h == 0 and w == 0:
            break
        ans = solve(h, w)
        print(ans)


if __name__ == '__main__':
    main(sys.argv[1:])

C++: #include <bits/stdc++.h>

using namespace std;
using i64 = long long;

bool solve(){
    int n,m;cin >> n >> m;
    if(n == 0)return 0;
    vector<string> vec;
    for(int i = 0;i < n;i++){
        string s;cin >> s;
        vec.push_back(s);
    }
    string s;cin >> s;
    long long ans = 0;
    pair<int,int> now = make_pair(0, 0);
    for(int i = 0;i < s.size();i++){
        bool t = false;
        for(int j = 0;j < n;j++){
            for(int k = 0;k < m;k++){
                if(vec.at(j).at(k) == s.at(i)){
                    t = true;
                    ans += abs(now.first - j);
                    ans += abs(now.second - k);
                    now = make_pair(j, k);
                    break;
                }
            }
            if(t)break;
        }
    }
    cout<<ans+s.size()<<endl;
    return true;
}

signed main()
{
    while(solve());
    return 0;
}

C++: #include<bits/stdc++.h>
using namespace std;
main(){
    int h,w;
    cin >> h >> w;
    while(h != 0){
    vector<vector<char> > scr(h,vector<char>(w));

    for(int i = 0;i<h;i++){
        for(int j = 0;j<w;j++){
            cin >> scr.at(i).at(j);
        }
    }

    string s;
    cin >> s;
    
    int bx=0;int by=0;
    // for(int i = 0;i<h;i++){
    //     for(int j = 0;j<w;j++){
    //         if(scr.at(i).at(j) == s[0]){
    //             bx=i;by=j;
    //         }
    //     }
    // }



    int ans = 0;

    for(int n = 0;n<s.length();n++){
        for(int i = 0;i<h;i++){
        for(int j = 0;j<w;j++){
            if(scr.at(i).at(j) == s[n]){
                ans += abs(bx-i) + abs(by-j) +1;
                bx=i;by=j;
            }
        }
    }
      
    }
    cout << ans << endl;
    cin >> h >> w;
    }
     
    


}

C++: #include<iostream>
#include<cmath>
#include<string>
#include<map>
using namespace std;
map<char, pair<int, int>>m;
string s;
signed main() {
	int h, w, x, y, ans;
	while (cin >> h >> w, h) {
		m.clear(); x = 0; y = 0; ans = 0;
		for (int i = 0; i < h; i++) {
			cin >> s;
			for (int j = 0; j < w; j++)if (s[j] != '_')m[s[j]] = make_pair(i, j);
		}
		cin >> s;
		for (int i = 0; i < s.size(); i++) {
			ans += abs(x - m[s[i]].first) + abs(y - m[s[i]].second);
			x = m[s[i]].first; y = m[s[i]].second;
		}cout << ans+s.size() << endl;
	}
}

C++: #include <bits/stdc++.h>
#include <type_traits>
using namespace std;

using ll = long long;

#define rep(i, n) for (int i = 0; i < (n); ++i)
#define rrep(i, n) for (int i = 1; i <= (n); ++i)
#define drep(i, n) for (int i = (n)-1; i >= 0; --i)
#define ddrep(i, n) for (int i = n; i > 0; --i)
#define srep(i, s, t) for (int i = s; i < t; ++i)
#define ssrep(i, s, t) for (int i = s; i <= t; ++i)

#define rng(a) a.begin(), a.end()
#define rrng(a) a.rbegin(), a.rend()
#define pb push_back
#define eb emplace_back
#define fi first
#define se second

#define chmax(x, y) (x = max(x, y))
#define chmin(x, y) (x = min(x, y))

using pi = pair<int, int>;
using vi = vector<int>;
using vvi = vector<vi>;
using vl = vector<ll>;
using vvl = vector<vl>;
using ld = long double;

template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
  os << "(" << p.first << "," << p.second << ")";
  return os;
}

template <class T> ostream &operator<<(ostream &os, const vector<T> &v) {
  os << "{";
  rep(i, (int)v.size()) {
    if (i)
      os << ",";
    os << v[i];
  }
  os << "}";
  return os;
}

template <typename T, size_t S> void printArray(const T (&array)[S]) {
  for (auto val : array)
    std::cout << val << ", ";
  std::cout << "\n";
}

const int mod = 1e9 + 7;
const int inf = 1e9 + 5;

void solve(int h, int w) {
  vector<string> key(h); rep(i, h) std::cin >> key[i];
  string in; std::cin >> in;
  map<char, int> cp;
  rep(i, h) rep(j, w) {
    cp[key[i][j]] = i*w+j;
  }
  int x = 0, y = 0;
  ll ans = 0;
  for (auto &c : in) {
    int nx = cp[c] % w, ny = cp[c] / w;
    int dx = abs(nx - x), dy = abs(ny - y);
    ans += dx + dy + 1;
    x = nx, y = ny;
  }
  std::cout << ans << "\n";
}

int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  cout << std::setprecision(10);

  while (1) {
    int h, w; std::cin >> h >> w;
    if (h == 0 && w == 0) break;
    solve(h, w);
  }
}