Problem:
On-Screen Keyboard
You are to input a string with an OSK (on-screen keyboard).
    A remote control with five buttons, four arrows and an OK (Fig. B-1),
    is used for the OSK.
    Find the minimum number of button presses required
    to input a given string with the given OSK.
Fig. B-1 Remote control
Fig. B-2 An on-screen keyboard
Character to input
Move of highlighted cells
Button presses
I
→,→,→,→,→,→,→,→,OK (9 presses)
C
←,←,←,←,←,←,OK (7 presses)
P
↓,→,→,→,→,OK (6 presses)
C
↑,←,←,←,←,OK (6 presses)
Fig. B-3 The minimum steps to input “
ICPC
” with the OSK in Fig. B-2
The OSK has cells arranged in a grid, each of which has a
    character in it or is empty.
    No two of the cells have the same character.
One of the cells of the OSK is highlighted, and
    pressing the OK button will input the character in that cell,
    if the cell is not empty.
Initially, the cell at the top-left corner is highlighted.
    Pressing one of the arrow buttons will change the highlighted cell
    to one of the adjacent cells in the direction of the arrow.
    When the highlighted cell is on an edge of the OSK,
    pushing the arrow button with the direction to go out of the edge
    will have no effect.
For example, using the OSK with its arrangement shown in Fig. B-2,
    a string “
ICPC
” can be input with 28 button presses
    as shown in Fig. B-3, which is the minimum number of presses.
Characters in cells of the OSKs are any of a lowercase letter
    (‘
a
’, ‘
b
’, ..., ‘
z
’),
    an uppercase letter
    (‘
A
’, ‘
B
’, ..., ‘
Z
’),
    a digit
    (‘
0
’, ‘
1
’, ..., ‘
9
’),
    a comma (‘
,
’),
    a hyphen (‘
-
’),
    a dot (‘
.
’),
    a slash (‘
/
’),
    a colon (‘
:
’),
    a semicolon (‘
;
’),
    or an at sign (‘
@
’).
Input
The input consists of at most 100 datasets, each in the following format.
h w
r
1
...
r
h
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 a space, 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,
r
i
is a string of length
w
.
  The characters in the string corresponds to the characters
in the cells of the
i
-th row of the OSK
or an underscore (‘
_
’) indicating an empty cell,
  from left 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 given OSK.
  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 to input 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,AsiaYokohamaRegiona
...(truncated)

Submitted solutions:

code_snippet: /*
 *   author : cellul4r
 */
#include<bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef long double ld;
typedef pair<int, int> pi;
typedef pair<ll,ll> pl;
typedef pair<ld,ld> pd;
#define all(x) x.begin(), x.end()
const char nl = '\n';
const int N =1e5+1;
const int INF = 1e9+7;
const ll LINF = 1e18+7;

const int dr[] = {-1,0,1,0}, dc[] = {0,1,0,-1};
void setIO(string);
void solve(){
    
    int n,m;
    cin>>n>>m;
    while(n != 0) {
        map<char, int> save;
        vector<vector<ll>> dist(n*m, vector<ll>(n*m,INF));
        for(int i = 0; i < n; i++) {
            string s;
            cin>>s;
            for(int j = 0; j < m; j++) {
                if(s[j] == '_') continue;
                save[s[j]] = m * i + j;
            }
        }

        for(int i = 0; i < n; i++) {
            for(int j = 0; j < m; j++) {
                queue<pi> Q;
                int now = m * i + j;
                dist[now][now] = 0;
                Q.push(make_pair(i,j));
                while(!Q.empty()) {
                    int ur = Q.front().first, uc = Q.front().second;
                    //cerr << ur << " I:J " << i << " : " << j << " " << uc << nl;
                    Q.pop();
                    for(int k = 0; k < 4; k++) {
                        int vr = ur + dr[k] , vc = uc + dc[k]; 
                        if(vr < 0 || vc < 0 || vr >= n || vc >= m || dist[now][m * vr + vc] != INF) continue;
                        dist[now][m * vr + vc] = dist[now][m * ur + uc] + 1; 
                        Q.push(make_pair(vr,vc));
                    }
                }
            }
        }
        string s; cin>>s;
        ll ans = s.size(); 
        int cur = 0;
        for(auto &x : s) {
            ans += dist[cur][save[x]];
            cur = save[x];
        }
        cout << ans << nl;
        cin>>n>>m;
    }
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int t = 1;

    //setIO("");
    //cin>>t;
    while(t--)solve();

    return 0;
}

void setIO(string s) {
    (void)!freopen((s + ".in").c_str(), "r", stdin);
    (void)!freopen((s + ".out").c_str(), "w", stdout);
}
accuracy: 1
time_ms: 1220
memory_kb: 51988
final_rank: 20

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;

int main(){
  while(true){
    int h, w;
    cin >> h >> w;
    if(!h) break;

    vector<string> keyboard(h);
    for(auto& i:keyboard) cin >> i;

    string target;
    cin >> target;

    int ans = 0;
    pair<int,int> locate = {0,0}; //{縦, 横}

    for(auto i:target){
      pair<int,int> goal; //{縦, 横}
      for(int j=0;j<h;j++){
        for(int k=0;k<w;k++){
          if(keyboard[j][k] == i){
            goal = {j,k};
          }
        }
      }
      ans += abs(locate.first-goal.first) + abs(locate.second-goal.second)+1;
      locate = goal;
    }

    cout << ans << endl;
  }
  return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 3468
final_rank: 13

code_snippet: #include<bits/stdc++.h>
using namespace std;
#define int long long

int solve(){
	int h,w;
	cin>>h>>w;
	if(h+w==0){
		return 0;
	}
	vector<vector<char>> board(h,vector<char>(w,'.'));
	for(int i=0;i<h;i++){
		for(int j=0;j<w;j++){
			cin>>board.at(i).at(j);
		}
	}
	string s;
	cin>>s;
	int x=0,y=0;
	int ans=0;
	for(int k=0;k<s.size();k++){
		for(int i=0;i<h;i++){
			for(int j=0;j<w;j++){
				if(board.at(i).at(j)==s.at(k)){
					ans+=abs(i-x)+abs(j-y);
					x=i,y=j;
				}
				
			}
		}
	}
	cout<<ans+s.size()<<endl;
	return 1;
}

#undef int
int main(){
	#define int long long
	while(solve()){}
}
accuracy: 1
time_ms: 20
memory_kb: 3372
final_rank: 11

code_snippet: #include <bits/stdc++.h>
using namespace std;
struct Init {
  Init() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout << setprecision(13);
  }
} init;

using ll = long long;
using ull = unsigned long long;
using VLL = vector<ll>;
using VVLL = vector<VLL>;
using PLL = pair<ll, ll>;
using VS = vector<string>;

#define rep(i, n) for (int i = 0; i < int(n); ++i)
#define FOR(i, a, b) for (int i = int(a); i < int(b); ++i)
#define all(x) (x).begin(), (x).end()
#define rall(x) x.rbegin(), x.rend()

const double PI = 3.141592653589793238;
const int INF = 1073741823;
const ll INFLL = 1LL << 60;
const string ABC = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const string abc = "abcdefghijklmnopqrstuvwxyz";
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};

template <typename T>
ostream& operator<<(ostream& os, const vector<T>& v) {
  for (int i = 0; i < (int)v.size(); i++)
    os << v[i] << (i + 1 != (int)v.size() ? " " : "");
  return os;
}
template <typename T>
istream& operator>>(istream& is, vector<T>& v) {
  for (T& in : v)
    is >> in;
  return is;
}
void print() {
  cout << '\n';
}
template <typename T>
void print(const T& t) {
  cout << t << '\n';
}
template <typename Head, typename... Tail>
void print(const Head& head, const Tail&... tail) {
  cout << head << ' ';
  print(tail...);
}
template <typename T1, typename T2>
inline bool chmax(T1& a, T2 b) {
  bool compare = a < b;
  if (compare)
    a = b;
  return compare;
}
template <typename T1, typename T2>
inline bool chmin(T1& a, T2 b) {
  bool compare = a > b;
  if (compare)
    a = b;
  return compare;
}

int main() {
  while (true) {
    int h, w;
    string s;
    cin >> h >> w;
    if (h == 0 && w == 0)
      return 0;
    vector<vector<char>> r(h, vector<char>(w));
    for (int i = 0; i < h; i++)
      for (int j = 0; j < w; j++)
        cin >> r.at(i).at(j);
    cin >> s;

    long long ans = 0;
    int now_y = 0, now_x = 0;
    for (char c : s) {  // cが入力しようとしている文字

      long long min_dist = 1e5;
      int min_y = 0, min_x = 0;
      for (int i = 0; i < h; i++) {
        for (int j = 0; j < w; j++) {
          if (r.at(i).at(j) != c)
            continue;
          int dist = abs(i - now_y) + abs(j - now_x) + 1;
          if (min_dist > dist) {
            min_dist = dist;
            min_y = i;
            min_x = j;
          }
        }
      }
      ans += min_dist;
      now_y = min_y;
      now_x = min_x;
    }

    cout << ans << endl;
  }
}
accuracy: 1
time_ms: 30
memory_kb: 3432
final_rank: 14

code_snippet: #include<bits/extc++.h>
#define rep(i,n) for(int i=0; i< (n); i++)
#define all(a) begin(a),end(a)
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
const int mod = 998244353;
const int inf = (1<<30);
const ll INF = (1ull<<62);
const int dx[8] = {1,0,-1,0,1,1,-1,-1};
const int dy[8] = {0,1,0,-1,1,-1,1,-1};
template< typename T1, typename T2 >
inline bool chmax(T1 &a, T2 b) { return a < b && (a = b, true); }
template< typename T1, typename T2 >
inline bool chmin(T1 &a, T2 b) { return a > b && (a = b, true); }


int main(){
    cin.tie(nullptr);
    ios_base::sync_with_stdio(false);
    cout.setf(ios_base::fixed);
    cout.precision(12);
    while (true){
        int h, w;
        cin >> h >> w;
        if (h == 0) break;
        vector<string> r(h);
        for (int i = 0; i < h; i++){
            cin >> r[i];
        }
        map<pair<char, char>, int> mp;
        for (int i = 0; i < h; i++){
            for (int j = 0; j < w; j++){
                for (int k = 0; k < h; k++){
                    for (int l = 0; l < w; l++){
                        mp[make_pair(r[i][j], r[k][l])] = abs(i - k) + abs(j - l);
                    }
                }
            }
        }
        string s;
        cin >> s;
        int ans = s.size();
        for (int i = 0; i < h; i++){
            for (int j = 0; j < w; j++){
                if (r[i][j] == s[0]){
                    ans += i + j;
                }
            }
        }
        for (int i = 0; i < (int) s.size() - 1; i++){
            ans += mp[make_pair(s[i], s[i + 1])];
        }
        cout << ans << endl;
    }
}
accuracy: 1
time_ms: 1070
memory_kb: 3656
final_rank: 19

code_snippet: #pragma region Macros
#include <bits/stdc++.h>
using namespace std;
using lint = long long;
using ull = unsigned long long;
using ld = long double;
using int128 = __int128_t;
#define all(x) (x).begin(), (x).end()
#define EPS 1e-8
#define uniqv(v) v.erase(unique(all(v)), v.end())
#define OVERLOAD_REP(_1, _2, _3, name, ...) name
#define REP1(i, n) for (auto i = std::decay_t<decltype(n)>{}; (i) != (n); ++(i))
#define REP2(i, l, r) for (auto i = (l); (i) != (r); ++(i))
#define rep(...) OVERLOAD_REP(__VA_ARGS__, REP2, REP1)(__VA_ARGS__)
#define log(x) cout << x << endl
#define logfixed(x) cout << fixed << setprecision(10) << x << endl;
#define logy(bool)         \
  if (bool) {              \
    cout << "Yes" << endl; \
  } else {                 \
    cout << "No" << endl;  \
  }

ostream &operator<<(ostream &dest, __int128_t value) {
  ostream::sentry s(dest);
  if (s) {
    __uint128_t tmp = value < 0 ? -value : value;
    char buffer[128];
    char *d = end(buffer);
    do {
      --d;
      *d = "0123456789"[tmp % 10];
      tmp /= 10;
    } while (tmp != 0);
    if (value < 0) {
      --d;
      *d = '-';
    }
    int len = end(buffer) - d;
    if (dest.rdbuf()->sputn(d, len) != len) {
      dest.setstate(ios_base::badbit);
    }
  }
  return dest;
}

template <typename T>
ostream &operator<<(ostream &os, const vector<T> &v) {
  for (int i = 0; i < (int)v.size(); i++) {
    os << v[i] << (i + 1 != (int)v.size() ? " " : "");
  }
  return os;
}

template <typename T>
ostream &operator<<(ostream &os, const set<T> &set_var) {
  for (auto itr = set_var.begin(); itr != set_var.end(); itr++) {
    os << *itr;
    ++itr;
    if (itr != set_var.end()) os << " ";
    itr--;
  }
  return os;
}

template <typename T, typename U>
ostream &operator<<(ostream &os, const map<T, U> &map_var) {
  for (auto itr = map_var.begin(); itr != map_var.end(); itr++) {
    os << itr->first << " -> " << itr->second << "\n";
  }
  return os;
}

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

void out() { cout << '\n'; }
template <class T, class... Ts>
void out(const T &a, const Ts &...b) {
  cout << a;
  (cout << ... << (cout << ' ', b));
  cout << '\n';
}

template <typename T>
istream &operator>>(istream &is, vector<T> &v) {
  for (T &in : v) is >> in;
  return is;
}

inline void in(void) { return; }
template <typename First, typename... Rest>
void in(First &first, Rest &...rest) {
  cin >> first;
  in(rest...);
  return;
}

template <typename T>
bool chmax(T &a, const T &b) {
  if (a < b) {
    a = b;
    return true;
  }
  return false;
}
template <typename T>
bool chmin(T &a, const T &b) {
  if (a > b) {
    a = b;
    return true;
  }
  return false;
}

vector<lint> dx8 = {1, 1, 0, -1, -1, -1, 0, 1};
vector<lint> dy8 = {0, 1, 1, 1, 0, -1, -1, -1};
vector<lint> dx4 = {1, 0, -1, 0};
vector<lint> dy4 = {0, 1, 0, -1};

#pragma endregion

int main() {
  cin.tie(0)->sync_with_stdio(0);
  int h, w;
  while (1) {
    in(h, w);
    if (h == 0 and w == 0) break;
    unsigned char b = '_';
    vector a(h, vector(w, b));
    in(a);

    vector d(256, vector(256, -1));
    if (a[0][0] == '_') a[0][0] = '%';
    rep(y1, h) rep(x1, w) rep(y2, h) rep(x2, w) {
      if (a[y1][x1] == '_' or a[y2][x2] == '_') continue;
      unsigned char c1 = a[y1][x1];
      unsigned char c2 = a[y2][x2];
      d[c1 - '\0'][c2 - '\0'] = abs(y1 - y2) + abs(x1 - x2) + 1;
      d[c2 - '\0'][c1 - '\0'] = abs(y1 - y2) + abs(x1 - x2) + 1;
    }
    string s;
    in(s);

    int n = s.size();
    unsigned char cur = a[0][0];
    lint res = 0;
    rep(i, n) {
      int nex = s[i] - '\0';
      res += d[cur][nex];
      cur = nex;
    }
    out(res);
  }
}
accuracy: 1
time_ms: 50
memory_kb: 3968
final_rank: 15

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

#define CHOOSE(a) CHOOSE2 a
#define CHOOSE2(a0, a1, a2, a3, a4, x, ...) x
#define debug_1(x1) std::cerr << #x1 << ": " << x1 << std::endl
#define debug_2(x1, x2) std::cerr << #x1 << ": " << x1 << ", " << #x2 << ": " << x2 << std::endl
#define debug_3(x1, x2, x3) std::cerr << #x1 << ": " << x1 << ", " << #x2 << ": " << x2 << ", " << #x3 << ": " << x3 << std::endl
#define debug_4(x1, x2, x3, x4) std::cerr << #x1 << ": " << x1 << ", " << #x2 << ": " << x2 << ", " << #x3 << ": " << x3 << ", " << #x4 << ": " << x4 << std::endl
#define debug_5(x1, x2, x3, x4, x5) std::cerr << #x1 << ": " << x1 << ", " << #x2 << ": " << x2 << ", " << #x3 << ": " << x3 << ", " << #x4 << ": " << x4 << ", " << #x5 << ": " << x5 << std::endl
#ifdef _DEBUG
#define debug(...) CHOOSE((__VA_ARGS__, debug_5, debug_4, debug_3, debug_2, debug_1, ~))(__VA_ARGS__)
#define debug_ary(a)                                                           \
    for (int i = 0; i < int(a.size()); i++) {                                  \
        std::cerr << #a << "[" << setw(2) << i << "]:" << (a)[i] << std::endl; \
    }
#define debug_sleep(a) sleep(a);
#define DBK std::cerr << "DBK" << std::endl;
#else
#define debug(...)
#define debug_ary(a)
#define debug_sleep(a)
#define DBK
#endif

#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define repn(i, a, n) for (int i = a; i < (int)(n); i++)
#define rrep(i, n) for (int i = n - 1; 0 <= i; i--)
#define all(a) (a).begin(), (a).end()
#define rall(a) (a).rbegin(), (a).rend()
template <class T>
constexpr T inf() { return ::numeric_limits<T>::max(); }
using ll = long long;
// max(int)=2*10^9
// max(long long)=9*10^18

int main() {
    while (true) {
        int h, w;
        cin >> h >> w;
        ll ans = 0;
        string str = "";
        // 初期の座標
        ll x = 0, y = 0;
        vector<vector<char>> key(h, vector<char>(w));
        if (h == 0 && w == 0) {
            break;
        }
        rep(i, h) {
            rep(j, w) {
                cin >> key[i][j];
            }
        }
        cin >> str;
        bool flag = false;
        rep(i, (ll)str.size()) {
            rep(j, h) {
                rep(k, w) {
                    if (str[i] == key[j][k]) {
                        ans += abs(x - j) + abs(y - k) + 1;
                        x = j;
                        y = k;
                        flag = true;
                        break;
                    }
                }
                if (flag == true) {
                    break;
                }
            }
            flag = false;
        }
        cout << ans << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 3360
final_rank: 1

code_snippet: #include<iostream>
#include<vector>
#include<algorithm>
#include<cmath>
#include<string>
#include<queue>
using namespace std;

#define rep(i, a, b) for(int i = a; i < (b); ++i)
#define all(x) begin(x), end(x)
#define sz(x) (int)(x).size()
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;

bool solve() {
	int H, W; cin >> H >> W;
	if (H == 0)return 0;

	vector<string>R(H);
	rep(i, 0, H)cin >> R[i];
	string S; cin >> S;
	
	const int inf = 100100100;
	vector<vector<int>> dp(H, vector<int>(W, inf));
	dp[0][0] = 0;

	for (auto tar : S) {

		vector<vector<int>> old(H, vector<int>(W, inf));
		swap(old, dp);
		queue<pii>q;
		rep(i, 0, H)rep(j, 0, W) if (old[i][j] < inf) {
			q.emplace(i, j);
			dp[i][j] = old[i][j];
		}
		while (!q.empty()) {
			int i = q.front().first;
			int j = q.front().second;
			q.pop();
			const int di[] = { 0,0,-1,1 };
			const int dj[] = { -1,1,0,0 };
			rep(d, 0, 4) {
				int ni = i + di[d];
				int nj = j + dj[d];
				if (ni < 0 || ni >= H || nj < 0 || nj >= W)continue;
				if (dp[ni][nj] > dp[i][j] + 1) {
					dp[ni][nj] = dp[i][j] + 1;
					q.emplace(ni, nj);
				}
			}
		}
		rep(i, 0, H)rep(j, 0, W) 
			if (R[i][j] != tar) dp[i][j] = inf;

	}

	int ans = inf;
	rep(i, 0, H)rep(j, 0, W)ans = min(ans, dp[i][j]);
	cout << ans+sz(S) << endl;
	return 1;
}
int main() {
	while(solve());
	return 0;
}
accuracy: 1
time_ms: 430
memory_kb: 3584
final_rank: 18

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
typedef long long ll;

int main() {
  vector<int> ans;
  while(true) {
    int h, w;
    cin >> h >> w;

    if (h == 0 && w == 0) break;


    vector<vector<char>> key(h, vector<char>(w));

    rep(i, h) {
      rep(j, w) {
        cin >> key[i][j];
      }
    }

    string s;
    cin >> s;


    int step = 0;
    ll sum = 0; 
    pair<int, int> p(0, 0);
    rep(k, s.size()) {
      bool found_char_for_s_k = false;
      rep(i, h) {
        rep(j, w) {
          if (key[i][j] == s[k]) {
            step = abs(p.first - i) + abs(p.second - j);
            p.first = i;
            p.second = j;
            sum += step+1;
            found_char_for_s_k = true;
            break;               
          }
        }
        if (found_char_for_s_k) {
          break;
        }
      }
    }

    ans.push_back(sum);
  }

  rep(i, ans.size()) {
    cout << ans[i] << endl;
  }
  return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 3372
final_rank: 2

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define rep(i,n)   for(int i=0;i<(n);i++)

int main(){
    while(1){
        int h,w;
        string s;
        cin>>h>>w;
        if(h==0&&w==0) return 0;
        vector<vector<char>> key(h,vector<char>(w));
        rep(i,h){
            rep(j,w){
                cin>>key[i][j];
            }
        }
        cin>>s;
        int curX=0,curY=0;
        int ans=0;
        rep(i,s.size()){
            bool done=false;
            queue<int> A;
            vector<vector<int>> dist(h,vector<int>(w,-1));
            A.push(curX);A.push(curY);
            dist[curX][curY]=0;
            while(!done){
                int x = A.front();A.pop();
                int y = A.front();A.pop();
                if(key[x][y]==s[i]){
                    done=true;
                    ans+=dist[x][y]+1;
                    curX=x;
                    curY=y;
                    break;
                }
                int dt=dist[x][y];
                if(x-1>=0){
                    if(dist[x-1][y]<0) {
                        A.push(x-1);A.push(y);dist[x-1][y]=dt+1;
                    }
                }
                if(x+1<h){
                    if(dist[x+1][y]<0){
                        A.push(x+1);A.push(y);dist[x+1][y]=dt+1;
                    }
                }
                if(y-1>=0){
                    if(dist[x][y-1]<0){
                        A.push(x);A.push(y-1);dist[x][y-1]=dt+1;
                    }
                }
                if(y+1<w){
                    if(dist[x][y+1]<0){
                        A.push(x);A.push(y+1);dist[x][y+1]=dt+1;
                    }
                }
            }
        }
        cout<<ans<<endl;
    }
}
accuracy: 1
time_ms: 180
memory_kb: 3444
final_rank: 16

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

int main(){
    vector<int> result;
    int h,w;
    string s;
    while(true){
        cin >> h >> w;
        if(h == 0 && w == 0){break;}
        vector<string> keybord(h);
        for(int i=0;i<h;i++){cin >> keybord.at(i);}
        cin >> s;
        pair<int,int> iti(0,0);
        int kyori = 0;
        int A = 0;
        int B = 0;
        for(int u=0;u<s.size();u++){
            char k = s.at(u);
            for(int i=0;i<h;i++){
                int P = 0;
                for(int j=0;j<w;j++){
                    if(k == keybord.at(i).at(j)){
                        A = abs(iti.first - i);
                        B = abs(iti.second - j);
                        kyori = kyori + A + B + 1;
                        iti.first = i;
                        iti.second = j;
                        P = 1;
                        break;
                    }
                }
                if(P == 1){break;}
            }
        }
        result.push_back(kyori);
    }
    for(int x:result){
        cout << x << endl;
    }
}
accuracy: 1
time_ms: 10
memory_kb: 3392
final_rank: 6

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

int main() {
    int h, w;
    vector<int> result;
    while (true) {
        cin >> h >> w;
        if (h == 0 && w == 0) break;

        vector<vector<char>> keybord(h, vector<char>(w));
        for (int i = 0; i < h; i++) {
            for (int j = 0; j < w; j++) {
                char c;
                cin >> c;
                keybord[i][j] = c;
            }
        }

        string str;
        cin >> str;

        int ans = 0;
        int posI = 0;
        int posJ = 0;
        for (char const& c : str) {
            for (int i = 0; i < h; i++) {
                for (int j = 0; j < w; j++) {
                    if (c == keybord[i][j]) {
                        ans += abs(posI - i) + abs(posJ - j) + 1;
                        posI = i;
                        posJ = j;
                        i = h;
                        break;
                    }
                }
            }
        }

        result.push_back(ans);
    }

    for (int const& a : result) {
        cout << a << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 3372
final_rank: 2

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, s, n) for (int i = (s); i < (int)(n); i++)

int main() {
    while(1){
        int n,m;
        cin>> n >>m;
        if(n==0&&m==0){
            break;
        }
        vector<vector<char>> key(n,vector<char>(m));
        rep(i,0,n){
            rep(j,0,m){
                cin>> key[i][j];
            }
        }
        string s;
        cin >> s;
        int x=0,y=0,ans=0;
        rep(i,0,s.size()){
            int flag=0;
            rep(j,0,n){
                rep(k,0,m){
                    if(key[j][k]==s.at(i)){
                        ans+=abs(k-x);
                        ans+=abs(j-y);
                        ans++;
                        x=k;
                        y=j;
                        flag++;
                        break;
                    }
                    if(flag==1){
                        break;
                    }
                }
            }
        }
        cout << ans << endl;

    }

    return (0);
}
accuracy: 1
time_ms: 10
memory_kb: 3384
final_rank: 4

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

int main() {
    while(true){
        int h, w;
        cin >> h >> w;
        if (h == 0 and w == 0) break;
        int Ans = 0;
        vector<vector<char>> Key(h, vector<char>(w));

        for (int i = 0; i < h; i++) {
            string r;
            cin >> r;
            for (int j = 0; j < w; j++) {
                Key.at(i).at(j) = r[j];
            }
        }

        string S;
        cin >> S;

        int x = 0;
        int y = 0;

        for (int i = 0; i < S.length(); i++) {
            for (int j = 0; j < h; j++) {
                for (int k = 0; k < w; k++) {
                    if (S[i] == Key[j][k]){
                        Ans =  Ans + abs(j-y) + abs(k-x) + 1;
                        x = k;
                        y = j;
                        j = h;
                        k = w;
                    }
                }
            }
            //Ans = Ans + 1;
        }

        cout << Ans << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 3384
final_rank: 4

code_snippet: #include <bits/stdc++.h>
#define rep(i,m,n) for(int i=m;i<n;i++)
#define REP(i,m,n) for(int i=m;i<=n;i++)
using namespace std;
using ll = long long;
int main(){
    rep(l,0,100){
        int h,w;
        cin>>h>>w;
        if(h==0&&w==0)return 0;
        char r[h][w];
        rep(i,0,h)rep(j,0,w)cin>>r[i][j];
        int x=0;
        int y=0;
        string s;
        cin>>s;
        int ans=0;
        rep(k,0,s.size()){
            rep(i,0,h)rep(j,0,w){
                if(r[i][j]==s[k]){
                    ans+=abs(x-i)+abs(y-j)+1;
                    x=i;y=j;
                }
            }
        }
        cout<<ans<<endl;
    }
}
accuracy: 1
time_ms: 20
memory_kb: 3328
final_rank: 10

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

using namespace std;
using ll = long long;

int main() {
    while (true) {
        int h, w;
        cin >> h >> w;
        if (h == 0 && w == 0) {
            break;
        }
        vector<string> r(h);
        for (int i = 0; i < h; i++) {
            cin >> r[i];
        }
        string s;
        cin >> s;

        int cx  = 0;
        int cy  = 0;
        int ans = 0;
        for (int i = 0; i < s.size(); i++) {
            int tx = -1;
            int ty = -1;
            for (int a = 0; a < h; a++) {
                for (int b = 0; b < w; b++) {
                    if (r[a][b] == s[i]) {
                        tx = a;
                        ty = b;
                        break;
                    }
                }
            }

            ans += abs(cx - tx) + abs(cy - ty) + 1;
            cx = tx;
            cy = ty;
        }

        cout << ans << endl;
    }
}
accuracy: 1
time_ms: 10
memory_kb: 3456
final_rank: 7

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

using namespace std;
using ll = long long;

int dx[] = {0, 1, 0, -1};
int dy[] = {-1, 0, 1, 0};

vector<vector<int>> bfs(int sx, int sy, int h, int w) {
    queue<pair<int, int>> q;
    vector<vector<int>> dist(h, vector<int>(w, -1));
    q.emplace(sx, sy);
    dist[sx][sy] = 0;
    while (!q.empty()) {
        auto [x, y] = q.front();
        q.pop();
        for (int dir = 0; dir < 4; dir++) {
            int nx = x + dx[dir];
            int ny = y + dy[dir];
            if (nx < 0 || nx >= h || ny < 0 || ny >= w) {
                continue;
            }

            if (dist[nx][ny] == -1) {
                dist[nx][ny] = dist[x][y] + 1;
                q.emplace(nx, ny);
            }
        }
    }

    return dist;
}

int main() {
    while (true) {
        int h, w;
        cin >> h >> w;
        if (h == 0 && w == 0) {
            break;
        }
        vector<string> r(h);
        for (int i = 0; i < h; i++) {
            cin >> r[i];
        }
        string s;
        cin >> s;

        int cx  = 0;
        int cy  = 0;
        int ans = 0;
        for (int i = 0; i < s.size(); i++) {
            auto d = bfs(cx, cy, h, w);

            int tx = -1;
            int ty = -1;
            for (int a = 0; a < h; a++) {
                for (int b = 0; b < w; b++) {
                    if (r[a][b] == s[i]) {
                        tx = a;
                        ty = b;
                        break;
                    }
                }
            }

            ans += d[tx][ty]+1;
            cx = tx;
            cy = ty;
        }

        cout << ans << endl;
    }
}
accuracy: 1
time_ms: 370
memory_kb: 3584
final_rank: 17

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main(){
    ll h,w;
    string s;
    ll count = 0;
    ll pre = 0;
    ll dx,dy;

    while(1){
        cin >> h >> w;
        if(h == 0 && w == 0)break;
        vector<char> key(h * 50 + w);

        for(ll i = 0; i < h; i++){
            for(ll t = 0; t < w; t++){
                cin >> key.at(i * 50 + t);
            }
        }

        cin >> s;

        for(ll i = 0; i < s.size(); i++){
            for(ll t = 0; t < h * 50 + w; t++){
                if(s.at(i) == key.at(t)){
                    dx = ll(t / 50) - ll(pre / 50);
                    dy = ll(t % 50) - ll(pre % 50);

                    if(dx < 0)dx *= -1;
                    if(dy < 0)dy *= -1;

                    count += dx + dy + 1;

                    pre = t;
                    break;
                }
            }

            //cout << dx << " " << dy << '\n';
        }
        
        cout << count << '\n';
        count = 0;
        pre = 0;

    }


    return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 3456
final_rank: 7

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i,n) for(int i=0;i<(n);i++)//0-indexed
#define REP(i,j,n) for(int i=j;i<(n);i++)
#define all(a) (a).begin(),(a).end()
#define sort(a) sort(all(a))
#define reverse(a) reverse(all(a))
#define INF 1e9

int dx[]={1,0,-1,0};
int dy[]={0,1,0,-1};

int main(){
    while(1){
    ll h,w;
    cin >> h >> w;
    if(h==0&&w==0)break;
    vector<vector<char>> s(h,vector<char>(w));
    rep(i,h){
        rep(j,w){
            cin>>s.at(i).at(j);
        }
    }
    string t;
    cin>>t;
    ll cnt=0;
    pair<ll, ll> now=make_pair(0,0);
    rep(i,t.length()){
        rep(j,h){
            rep(k,w){
                if(s.at(j).at(k)==t.at(i)){
                    cnt+=(abs(j-now.first)+abs(k-now.second)+1);
                    now.first=j;
                    now.second=k;
                }
            }
        }
    }
    cout<<cnt<<endl;
}
}
accuracy: 1
time_ms: 20
memory_kb: 3376
final_rank: 12

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using ull = unsigned long long;

#define rep(i,n) for(ll i=0;i<n;++i)
#define all(a) (a).begin(),(a).end()
ll intpow(ll a, ll b){ ll ans = 1; while(b){ if(b & 1) ans *= a; a *= a; b /= 2; } return ans; }
ll modpow(ll a, ll b, ll p){ ll ans = 1; while(b){ if(b & 1) (ans *= a) %= p; (a *= a) %= p; b /= 2; } return ans; }
template<class T> T div_floor(T a, T b) { return a / b - ((a ^ b) < 0 && a % b); }
template<class T> T div_ceil(T a, T b) { return a / b + ((a ^ b) > 0 && a % b); }
template <typename T, typename U> inline bool chmin(T &x, U y) { return (y < x) ? (x = y, true) : false; }
template <typename T, typename U> inline bool chmax(T &x, U y) { return (x < y) ? (x = y, true) : false; }


void solve(ll H,ll W) {
    vector<string> A(H);
    rep(i,H){
        cin>>A[i];
    }
    string S;
    cin>>S;
    ll ci=0,cj=0;
    ll cnt=0;
    for (auto si:S){
        bool flag=false;
        rep(i,H){
            rep(j,W){
                if (si==A[i][j]){
                    cnt+=abs(i-ci)+abs(j-cj)+1;
                    ci=i;
                    cj=j;
                    flag=true;  
                    break;
                }
            }
            if (flag)break;
        }
    }
    cout<<cnt<<endl;
    return;
}


int main() {
    ll H,W;
    while (true){
        cin>>H>>W;
        if (H==0){
            break;
        }
        solve(H,W);
    }
    return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 3456
final_rank: 7