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

const int INF = 1e9;

int main()
{
	int H, W;
	char sc, tc;
	cin >> H >> W >> sc >> tc;
	int s = sc - 'A', t = tc - 'A';
	vector<string> S(H);
	vector<vector<int>> G(26);
	for (int i = 0; i < H; i++) {
		cin >> S[i];
	}
	for (int i = 0; i < H; i++) {
		for (int j = 0; j < W; j++) {
			if (S[i][j] == '-') {
				int u = S[i][j - 2] - 'A';
				int p = j;
				while (S[i][p] == '-') {
					S[i][p] = '.';
					p++;
				}
				int v = S[i][p + 1] - 'A';
				G[u].push_back(v);
				G[v].push_back(u);
			}
			if (S[i][j] == '|') {
				int u = S[i - 2][j] - 'A';
				int p = i;
				while (S[p][j] == '|') {
					S[p][j] = '.';
					p++;
				}
				int v = S[p + 1][j] - 'A';
				G[u].push_back(v);
				G[v].push_back(u);
			}
		}
	}
	queue<int> q;
	vector<int> d(26, INF);
	q.push(s);
	d[s] = 0;
	while (!q.empty()) {
		auto v = q.front(); q.pop();
		for (auto to : G[v]) if (d[to] == INF) {
			q.push(to);
			d[to] = d[v] + 1;
		}
	}
	cout << d[t] << endl;
	return 0;
}

