/*@author Vipen Loka*/
#include <bits/stdc++.h>
#define endl '\n'
#define ff first
#define ss second
#define ll long long
#define vi vector<int>
#define vll vector<ll>
#define vvi vector < vi >
#define pii pair<int,int>
#define pll pair<long long, long long>
#define mod 1000000007
#define inf 1000000000000000001;
#define deb(x) cout << #x << ':' << x << '\n';

using namespace std;
template<class T>void show(vector<T> &a) {cerr << "[ "; for (int ij = 0; ij < (int)a.size(); ij++) {cerr << a[ij] << " ";} cerr << "]\n";}
template<class T>void show(T a) {cerr << a << endl;}
template<typename... T>void show(T... args) {((cerr << args << ' '), ...); cerr << endl;}
template<class T>void read(vector<T> &a) {for (auto &x : a) {cin >> x;}}
template<class T> void read(T &a) {cin >> a;}

void solve() {
	int i, j;
	int x, y;

	cin >> x >> y;

	if (x > y)swap(x, y);

	if (x == 0 && y == 1) {
		cout << 2 << endl;
	}
	else if (x == 1 && y == 2) {
		cout << 0 << endl;
	}
	else if (x == 0 && y == 2) {
		cout << 1 << endl;
	}
	else {
		cout << x << endl;
	}

}


int32_t main(int32_t argc, char *argv[]) {
	ios_base::sync_with_stdio(false);
	cin.tie(0);

	int T = 1;
	// cin >> T;
	while (T--) {
		solve();
	}
	cerr << "time taken : " << (float)clock() / CLOCKS_PER_SEC << " secs" << endl;
}
#include<bits/stdc++.h>
using namespace std;
int n,m;
const int Maxn=2010;
const int INF=0x3f3f3f3f;
const int dx[4]={1,-1,0,0};
const int dy[4]={0,0,1,-1};
typedef pair<int,int> pii;
vector<int>from[Maxn*Maxn];
char s[Maxn][Maxn];
int dist[Maxn*Maxn];
int st,ed;

void dij(){
	memset(dist,INF,sizeof(dist));
	priority_queue<pii>q;
	dist[st]=0;
	q.push(make_pair(0,st));
	while(!q.empty()){
		int u=q.top().second;
		int d=-q.top().first;
		q.pop();
		if(d>dist[u])continue;
		for(int i=0;i<(int)from[u].size();i++){
			int to=from[u][i];
			int cost=d;
			if(u<n*m)cost++;
			if(dist[to]>cost){
				dist[to]=cost;
				q.push(make_pair(-cost,to));
			}
		}
	}
}

int main(){
	scanf("%d%d",&n,&m);
	for(int i=0;i<n;i++){
		scanf("%s",s[i]);
		for(int j=0;j<m;j++){
			if(s[i][j]=='S')st=i*m+j;
			if(s[i][j]=='G')ed=i*m+j;
		}
	}
	for(int i=0;i<n;i++){
		for(int j=0;j<m;j++)if(s[i][j]!='#'){
			for(int d=0;d<4;d++){
				int nx=i+dx[d];
				int ny=j+dy[d];
				if(nx>=0&&nx<n&&ny>=0&&ny<m&&s[nx][ny]!='#'){
					from[i*m+j].push_back(nx*m+ny);
				}
			}
			if(s[i][j]>='a'&&s[i][j]<='z'){
				from[i*m+j].push_back(n*m+s[i][j]-'a');
				from[n*m+s[i][j]-'a'].push_back(i*m+j);
			}
		}
	}
	dij();
	if(dist[ed]==INF)printf("-1\n");
	else printf("%d\n",dist[ed]);
	return 0;
}