#include <bits/stdc++.h>
#define maxn 2010
using namespace std;
namespace IO {
char *p1, *p2, buf[15000];
#define nc() getchar()
inline int read() {
int x = 0, f = 1;
char ch = nc();
while (ch < 48 || ch > 57) {
if (ch == '-')
f = -1;
ch = nc();
}
while (ch >= 48 && ch <= 57)
x = (x << 1) + (x << 3) + (ch ^ 48),
ch = nc();
return x * f;
}
}
using IO::read;
char ch[maxn][maxn];
int r, c;
struct node {
int x, y, len, step;
};
queue<node> q;
int _nxt[4][2] = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
struct Tmp {
int x, y;
} tmp[4][maxn][maxn];
int Len;
int vis[maxn][maxn];
bool book[maxn][maxn];
int mi = INT_MAX;
char s[maxn * 5];
string str;
void init() {
for (int i = 1; i <= r; i++) {
for (int j = 1; j <= c; j++) {
for (int k = 0; k < 4; k ++) {
int tx = i, ty = j;
while (ch[tx][ty] == ch[tx + _nxt[k][0]][ty + _nxt[k][1]]) {
tx += _nxt[k][0], ty += _nxt[k][1];
}
tmp[k][i][j] = (Tmp) {
tx, ty
};
}
}
}
}
void bfs() {
int tx, ty;
while (!q.empty()) {
int x = q.front().x, y = q.front().y, len = q.front().len, step = q.front().step;
q.pop();
cout << len << endl;
if (len == Len + 1) {
cout << "OK" << endl;
mi = min(mi, step);
return;
}
if (ch[x][y] == s[len]) {
q.push((node) {
x, y, len + 1, step + 1
});
vis[x][y] = max(vis[x][y], len + 1);
}
for (int i = 0; i < 4; i++) {
tx = tmp[i][x][y].x + _nxt[i][0], ty = tmp[i][x][y].y + _nxt[i][1];
if (tx < 1 || ty < 1 || tx > r || ty > c) continue;
if (len > vis[tx][ty]) {
q.push((node) {
tx, ty, len, step + 1
});
vis[tx][ty] = len;
}
}
}
}
int main() {
r = read(), c = read();
for (int i = 1; i <= r; i++) {
cin >> str;
for (int j = 1; j <= c; j++) {
ch[i][j] = str[j - 1];
book[i][j] = true;
}
}
scanf("%s", s);
Len = strlen(s);
init();
if (ch[1][1] == s[0]) q.push((node) {
1, 1, 1, 1
}), vis[1][1] = 1;
for (int i = 0; i < 4; i++) {
int tx = tmp[i][1][1].x + _nxt[i][0];
int ty = tmp[i][1][1].y + _nxt[i][1];
if(tx < 1 || ty < 1 || tx > r || ty > c) continue;
q.push((node) {tx, ty, 0, 1});
}
bfs();
cout << mi;
return 0;
}