#include <bits/stdc++.h>
using namespace std;
// hotline miami ost went hard during this

int main() {
  ios::sync_with_stdio(0);
  cin.tie(nullptr);
  int dx[] = {-1, 1, 0, 0};
  int dy[] = {0, 0, -1, 1};

  int n, m;
  cin >> n >> m;
  vector<string> mapa(n);
  for (int i = 0; i < n; i++)
    cin >> mapa[i];

  vector<vector<int>> vatraT(n, vector<int>(m, INT_MAX));
  queue<pair<int, int>> vatra;
  pair<int, int> start;

  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      if (mapa[i][j] == 'X') {
        vatra.push({i, j});
        vatraT[i][j] = 0;
      } else if (mapa[i][j] == 'S')
        start = {i, j};
    }
  }

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

    for (int d = 0; d < 4; d++) {
      int nx = x + dx[d], ny = y + dy[d];
      if (nx >= 0 && nx < n && ny >= 0 && ny < m && mapa[nx][ny] == '.' &&
          vatraT[nx][ny] == INT_MAX) {
        vatraT[nx][ny] = vatraT[x][y] + 1;
        vatra.push({nx, ny});
      }
    }
  }

  // frkno comeback
  queue<tuple<int, int, int>> stev;
  vector<vector<bool>> posetio(n, vector<bool>(m, false));

  stev.push({start.first, start.second, 0});

  posetio[start.first][start.second] = true;

  int moguca_polja = 0;

  // death grips went hard during this

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

    if (t < vatraT[x][y])
      moguca_polja++;

    for (int d = 0; d < 4; d++) {
      int nx = x + dx[d];
      int ny = y + dy[d];
      if (nx >= 0 && nx < n && ny >= 0 && ny < m && mapa[nx][ny] == '.' &&
          !posetio[nx][ny] && t + 1 < vatraT[nx][ny]) {
        posetio[nx][ny] = true;
        stev.push({nx, ny, t + 1});
      }
    }
  }
  cout << moguca_polja << endl;
}