//----------------------------
#define FOR(i,j,n) for (int i=(j);i<(n);i++)
#define REP(i,n) for (int i=0;i<(n);i++)
#define REPN(i,n) for (int i=(n);i>=0;i--)
#define I(n) scanf("%d", &(n))
#define LL(n) scanf("%lld", &(n))
#define pb(n) push_back((n))
#define mp(i,j) make_pair((i),(j))
#include <bits/stdc++.h>
using namespace std;

//------------------------------typedef集
typedef vector<int> vi;
typedef pair<int,int> pi;
typedef vector<pi> vpi;
typedef vector<vi> vvi;
typedef vector<vpi> vvpi;
typedef vector<vvi> vvvi;
typedef long long ll;

int H,W,x,y,mv;
char s,t;
vpi vertex(28);
int adj[26][26],depth[26],exist[26];
string table[51];

int main(){
    cin >> H >> W >> s >> t ;
    REP(i,H){
        cin >> table[i];
        REP(j,W){
            if ('A' <= table[i][j] && table[i][j] <= 'Z'){
                vertex[table[i][j] - 'A'] = {i,j};
                exist[table[i][j] - 'A'] = 1;
            }
        }
    }
    REP(i,26){
        if (! exist[i]) continue;
        y = vertex[i].first;
        x = vertex[i].second;
        if (y >= 2 && table[y-2][x] == '|'){
            mv = y-2;
            while (table[mv][x] == '|') mv--;
            char conn = table[mv-1][x];
            adj[i][conn-'A'] = adj[conn-'A'][i] = 1;
        }
        if (y < H-2 && table[y+2][x] == '|'){
            mv = y+2;
            while (table[mv][x] == '|') mv++;
            char conn = table[mv+1][x];
            adj[i][conn-'A'] = adj[conn-'A'][i] = 1;
        }
        if (x >= 2 && table[y][x-2] == '-'){
            mv = x-2;
            while (table[y][mv] == '-') mv--;
            char conn = table[y][mv-1];
            adj[i][conn-'A'] = adj[conn-'A'][i] = 1;
        }
        if (x < W-2 && table[y][x+2] == '-'){
            mv = x+2;
            while (table[y][mv] == '-') mv++;
            char conn = table[y][mv+1];
            adj[i][conn-'A'] = adj[conn-'A'][i] = 1;
        }
    }

    deque<pi> q;
    q.push_back(mp(0,(s-'A')));

    while (!q.empty()){
        pi tp = q.front();
        q.pop_front();
        depth[tp.second] = tp.first;
        REP(i,26) if (adj[i][tp.second] && !depth[i] && i != s-'A') q.pb(mp(tp.first+1,i));
    }
    cout << depth[t-'A'] << endl;
}

