#include <bits/stdc++.h>
using namespace std;
int N, M, iS, jS;
char A[1006][1006];
int DIST[1006][1006];
int di[4] = {-1, 0, 1, 0};
int dj[4] = {0, -1, 0, 1};
inline int BFS()
{
  int RET = 0, i, j, d;
  queue <int> QI; queue <int> QJ; queue <int> QD;
  for(int i = 1; i <= N; i++)
  {
    for(int j = 1; j <= M; j++)
    {
      if(A[i][j] == 'X') {A[i][j] = '*'; QI.push(i); QJ.push(j);}
      else if(A[i][j] == 'S') {A[i][j] = '*'; iS = i; jS = j;}
      else DIST[i][j] = INT_MAX;
    }
  }
  while(QI.size())
  {
    i = QI.front(); j = QJ.front();
    for(int k = 0; k < 4; k++)
    {
      if((A[i + di[k]][j + dj[k]] != '*') && (DIST[i + di[k]][j + dj[k]] == INT_MAX))
      {
        DIST[i + di[k]][j + dj[k]] = DIST[i][j] + 1;
        QI.push(i + di[k]); QJ.push(j + dj[k]);
      }
    }
    QI.pop(); QJ.pop();
  }
  QI.push(iS); QJ.push(jS); QD.push(0);
  while(QI.size())
  {
    RET++;
    i = QI.front(); j = QJ.front(); d = QD.front();
    for(int k = 0; k < 4; k++)
    {
      if((A[i + di[k]][j + dj[k]] != '*') && ((d + 1) < DIST[i + di[k]][j + dj[k]]))
      {
        A[i + di[k]][j + dj[k]] = '*';
        QI.push(i + di[k]); QJ.push(j + dj[k]); QD.push(d + 1);
      }
    }
    QI.pop(); QJ.pop(); QD.pop();
  }
  return RET;
}
int main()
{
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  memset(A, '*', sizeof(A));
  cin >> N >> M;
  string S;
  for(int i = 1; i <= N; i++)
  {
    for(int j = 1; j <= M; j++) cin >> A[i][j];
  }
  cout << BFS() << '\n';

  return 0;
}