#include <iostream>
#include <vector>

using namespace std;

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

int main() {
    int N, M;
    cin >> N >> M;
    vector<string> l(N);
    pair<int, int>SP;
    vector<pair<int,int>> VC, sc;
    vector<vector<int>> VVr(N, vector<int>(M, -1));
    vector<vector<int>> Svr(N, vector<int>(M, -1));
    for(int i=0;i<N;++i) {
        cin >> l[i];
        for (int j = 0;j<M;++j) {
            if(l[i][j]=='X') {
                VC.push_back({i, j});
                VVr[i][j]=0;
            }else if(l[i][j]=='S') {
                SP={i, j};
                Svr[i][j]=0;
            }
        }
    }
    int FI=0;
    while (FI<VC.size()) {
        auto [x, y]=VC[FI++];
        for (int i=0;i<4;++i){
            int nx=x+dx[i],ny=y+dy[i];
            if(nx>=0 and ny>=0 and nx<N and ny<M and l[nx][ny]=='.' and VVr[nx][ny]==-1) {
                VVr[nx][ny] = VVr[x][y] + 1;
                VC.push_back({nx, ny});
            }
        }
    }
    sc.push_back(SP);
    int SI= 0;
    while(SI<sc.size()) {
        auto [x, y]=sc[SI++];
        for(int i=0;i<4;++i) {
            int nx = x + dx[i], ny = y + dy[i];
            if (nx >= 0 and ny >= 0 && nx <N && ny< M && l[nx][ny] == '.' && Svr[nx][ny] == -1) {
                if (VVr[nx][ny] == -1 || Svr[x][y] + 1 < VVr[nx][ny]) {
                    Svr[nx][ny] = Svr[x][y] + 1;
                    sc.push_back({nx, ny});
                }
            }
        }
    }
    int P= 0;
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < M; ++j) {
            if (l[i][j] == '.' && Svr[i][j] != -1 &&
                (VVr[i][j] == -1 || Svr[i][j] < VVr[i][j])) {
                P++;
            }
        }
    }
    P=P+1;
    cout<<P<<endl;
    return 0;
}