
#include <stdio.h>
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;

#define INF 1 << 15

typedef pair<int, int> P;

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

int X,Y;
int d[12][12],dd[12][12];
int IceNum, Ice[144];
P S,G;

queue<P> que;

bool check(int NX, int NY)
{
	if(NX >= X || NY >= Y || NX < 0 || NY < 0)
		return false;
	return true;
}

void dfs(P pos, int now)
{
	if(pos == G){
		dd[pos.second][pos.first] = min(dd[pos.second][pos.first], now);
		return;
	}
	if(now > dd[pos.second][pos.first])
		return;

	dd[pos.second][pos.first] = now;

	int nx,ny;
	for(int i = 0; i < 4; i++){
		nx = pos.first + dx[i], ny = pos.second + dy[i];
		if(check(nx,ny) && d[ny][nx] != -1){
			if(d[ny][nx] > 0){
				if(Ice[ d[ny][nx] ] > 0){
					Ice[ d[ny][nx] ]--;
					dfs(P(nx,ny), now+1);
					Ice[ d[ny][nx] ]++;
				}
			}
			else
				dfs(P(nx,ny), now+1);
		}
	}


		
}
int main(void)
{
	while(cin >> X >> Y, X > 0 && Y > 0){
		fill(&dd[0][0],&dd[0][0]+144, INF);
		fill(&Ice[0],&Ice[0]+144, 0);
		IceNum = 0;
		char s[13];

		for(int i = 0; i < Y; i++){
			scanf("%s", s);
			for(int j = 0; s[j] != '\0'; j++){
				if(s[j] == '.')
					d[i][j] = 0;
				else if(s[j] == '#')
					d[i][j] = -1;
				else if(s[j] == 'X')
					d[i][j] = -2;
				else if(s[j] == 'S')
					S = P(j,i),d[i][j] = 0;
				else if(s[j] == 'G')
					G = P(j,i),d[i][j] = 0;
			}
		}
		for(int i = 0; i < Y; i++){
			for(int j = 0; j < X; j++){
				if(d[i][j] == -2){
					IceNum++;
					
					que.push(P(j,i));

					while(que.size()){

						P p = que.front();
						que.pop();
						d[p.second][p.first] = IceNum;
						Ice[IceNum]++;
						int nx,ny;
						for(int i = 0; i < 4; i++){
							nx = p.first + dx[i], ny = p.second + dy[i];
							if(check(nx,ny) && d[ny][nx] == -2){
								que.push(P(nx,ny));
							}
						}
					}


				}

			}
		}

		for(int i = 0; i < 144; i++)
			Ice[i] /= 2;

		dfs(S,0);
		printf("%d\n", dd[G.second][G.first]);

	}

	return 0;
}