#include <bits/stdc++.h>
#define ll long long

using namespace std;

char G[1001][1001];
int vatra[1001][1001];
int steva[1001][1001];
int N, M;

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

int main()
{
  ios_base::sync_with_stdio(0);
  cin.tie(0);

  queue<pair<int, int>> vatra_q;
  queue<pair<int, int>> steva_q;

  cin >> N >> M;
  for (int i = 0; i < N; i++)
  {
    for (int j = 0; j < M; j++)
    {
      cin >> G[i][j];
      if (G[i][j] == 'X')
      {
        vatra_q.push({i, j});
        vatra[i][j] = 1;
      }
      else if (G[i][j] == 'S')
      {
        steva_q.push({i, j});
        steva[i][j] = 1;
        G[i][j] = '.';
      }
    }
  }

  while (!vatra_q.empty())
  {
    auto [x, y] = vatra_q.front();
    vatra_q.pop();

    for (int i = 0; i < 4; i++)
    {
      int nx = x + dx[i];
      int ny = y + dy[i];

      if (nx < 0 || nx >= N || ny < 0 || ny >= M || G[nx][ny] != '.' || vatra[nx][ny] != 0)
        continue;

      vatra_q.push({nx, ny});
      vatra[nx][ny] = vatra[x][y] + 1;
    }
  }

  int cnt = 1;
  while (!steva_q.empty())
  {
    auto [x, y] = steva_q.front();
    steva_q.pop();

    for (int i = 0; i < 4; i++)
    {
      int nx = x + dx[i];
      int ny = y + dy[i];

      if (nx < 0 || nx >= N || ny < 0 || ny >= M || G[nx][ny] != '.' || steva[nx][ny] != 0 || (vatra[nx][ny] != 0 && vatra[nx][ny] <= steva[x][y] + 1))
        continue;

      steva_q.push({nx, ny});
      steva[nx][ny] = steva[x][y] + 1;
      cnt++;
    }
  }

  cout << cnt << "\n";
}