#include <bits/stdc++.h>
using namespace std;

int n, m, sa, sb, br;
int nizi[] = {1, 0, -1, 0};
int nizj[] = {0, 1, 0, -1};
queue<int> kjur;
queue<int> kjuc;
char mat[1015][1015];
int korvat[1015][1015];
int korste[1015][1015];

void bfs() {
    while (!kjur.empty()) {
        int x = kjur.front();
        int y = kjuc.front();
        kjur.pop();
        kjuc.pop();

        for (int k = 0; k < 4; k++) {
            int nx = x + nizi[k];
            int ny = y + nizj[k];
            if (mat[nx][ny] != '*' && korvat[nx][ny] == -1) {
                korvat[nx][ny] = korvat[x][y] + 1;
                kjur.push(nx);
                kjuc.push(ny);
            }
        }
    }
}

void trace() {
    while (!kjur.empty()) {
        int x = kjur.front();
        int y = kjuc.front();
        kjur.pop();
        kjuc.pop();

        if (korste[x][y] < korvat[x][y] or korvat[x][y]==-1 and korste[x][y]>-1) br++;

        for (int k = 0; k < 4; k++) {
            int nx = x + nizi[k];
            int ny = y + nizj[k];
            if (mat[nx][ny] != '*' && korste[nx][ny] == -1) {
                korste[nx][ny] = korste[x][y] + 1;
                kjur.push(nx);
                kjuc.push(ny);
            }
        }
    }
}

int main() {
    cin >> n >> m;

    memset(mat,'*',sizeof(mat));
    memset(korvat, -1, sizeof(korvat));
    memset(korste, -1, sizeof(korste));

    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            cin >> mat[i][j];
            if (mat[i][j] == 'X') {
                kjur.push(i);
                kjuc.push(j);
                korvat[i][j] = 0;
            }
            if (mat[i][j] == 'S') {
                sa = i;
                sb = j;
            }
        }
    }

    bfs();

    kjur.push(sa);
    kjuc.push(sb);
    korste[sa][sb] = 0;

    trace();

    cout << br << endl;

    return 0;
}