#include <bits/stdc++.h>

using namespace std;

struct pos{
  int x;
  int y;

  pos(int x, int y) : x(x), y(y) {}
};

int main(){

  ios_base::sync_with_stdio(0);
  cin.tie(0);

  int n, m;

  cin >> n >> m;

  vector<vector<char>> mx(n, vector<char>(m));

  for(int i = 0; i < n; ++i){
    for(int j = 0; j < m; ++j) cin >> mx[i][j];
  }

  queue<pos> bfs, newBfs;
  vector<vector<int>> fire(n, vector<int>(m, -1)), steve(n, vector<int>(m, -1));

  for(int i = 0; i < n; ++i){
    for(int j = 0; j < m; ++j){
      if(mx[i][j] == 'S'){
        bfs.emplace(j, i);
        steve[i][j] = 0;
        break;
      }
    }
  }

  int curStep = 1;
  while(!bfs.empty()){
    pos curPos = bfs.front();
    bfs.pop();

    if(curPos.x-1 >= 0 && mx[curPos.y][curPos.x-1] == '.' && steve[curPos.y][curPos.x-1] == -1){
      newBfs.emplace(curPos.x-1, curPos.y);
      steve[curPos.y][curPos.x-1] = curStep;
    }

    if(curPos.y-1 >= 0 && mx[curPos.y-1][curPos.x] == '.' && steve[curPos.y-1][curPos.x] == -1){
      newBfs.emplace(curPos.x, curPos.y-1);
      steve[curPos.y-1][curPos.x] = curStep;
    }

    if(curPos.x+1 < m && mx[curPos.y][curPos.x+1] == '.' && steve[curPos.y][curPos.x+1] == -1){
      newBfs.emplace(curPos.x+1, curPos.y);
      steve[curPos.y][curPos.x+1] = curStep;
    }

    if(curPos.y+1 < n && mx[curPos.y+1][curPos.x] == '.' && steve[curPos.y+1][curPos.x] == -1){
      newBfs.emplace(curPos.x, curPos.y+1);
      steve[curPos.y+1][curPos.x] = curStep;
    }

    if(bfs.empty()) bfs = newBfs, newBfs = queue<pos>(), ++curStep;
  }

  bfs = queue<pos>(), newBfs = queue<pos>();
  for(int i = 0; i < n; ++i){
    for(int j = 0; j < m; ++j){
      if(mx[i][j] == 'X'){
        bfs.emplace(j, i);
        fire[i][j] = 0;
      }
    }
  }

  curStep = 1;
  while(!bfs.empty()){
    pos curPos = bfs.front();
    bfs.pop();

    if(curPos.x-1 >= 0 && mx[curPos.y][curPos.x-1] != '*' && fire[curPos.y][curPos.x-1] == -1){
      newBfs.emplace(curPos.x-1, curPos.y);
      fire[curPos.y][curPos.x-1] = curStep;
    }

    if(curPos.y-1 >= 0 && mx[curPos.y-1][curPos.x] != '*' && fire[curPos.y-1][curPos.x] == -1){
      newBfs.emplace(curPos.x, curPos.y-1);
      fire[curPos.y-1][curPos.x] = curStep;
    }

    if(curPos.x+1 < m && mx[curPos.y][curPos.x+1] != '*' && fire[curPos.y][curPos.x+1] == -1){
      newBfs.emplace(curPos.x+1, curPos.y);
      fire[curPos.y][curPos.x+1] = curStep;
    }

    if(curPos.y+1 < n && mx[curPos.y+1][curPos.x] != '*' && fire[curPos.y+1][curPos.x] == -1){
      newBfs.emplace(curPos.x, curPos.y+1);
      fire[curPos.y+1][curPos.x] = curStep;
    }

    if(bfs.empty()) bfs = newBfs, newBfs = queue<pos>(), ++curStep;
  }

  int cnt = 0;

  for(int i = 0; i < n; ++i){
    for(int j = 0; j < m; ++j){
      if(steve[i][j] == -1) continue;
      if(fire[i][j] == -1 || steve[i][j] < fire[i][j]) ++cnt;
    }
  }

  cout << cnt << '\n';

  return 0;
}