#include <iostream>
#include <queue>
#include <vector>
#include <tuple>

using namespace std;

const int dx[] = {-1, 1, 0, 0};
const int dy[] = {0, 0, -1, 1};
void vatra(queue<tuple<int, int, int>>& vr, vector<vector<int>>& vt, int n, int m, vector<string>& a) {
    while (!vr.empty()) {
        auto [x, y, time] = vr.front();
        vr.pop();
        for (int i = 0; i < 4; i++) {
            int nx = x + dx[i], ny = y + dy[i];
            if (nx >= 0 && nx < n && ny >= 0 && ny < m && vt[nx][ny] == -1 && a[nx][ny] != '*') {
                vt[nx][ny] = time + 1;
                vr.emplace(nx, ny, time + 1);
            }
        }
    }
}
void stivaa(int x1, int y1, const vector<vector<int>>& ft, vector<vector<int>>& st, int n, int m,  vector<string>& a) {
    queue<pair<int, int>> redic;
    redic.emplace(x1, y1);
    st[x1][y1] = 0;

    while (!redic.empty()) {
        auto [x, y] = redic.front();
        redic.pop();
        for (int i = 0; i < 4; i++) {
            int nx = x + dx[i], ny = y + dy[i];
            if (nx >= 0 && nx < n && ny >= 0 && ny < m && st[nx][ny] == -1 && a[nx][ny] != '*') {
                if (ft[nx][ny] == -1 || st[x][y] + 1 < ft[nx][ny]) {
                    st[nx][ny] = st[x][y] + 1;
                    redic.emplace(nx, ny);
                }
            }
        }
    }
}

int main() {
    ios::sync_with_stdio(false);
    int n, m;
    cin >> n >> m;
    vector<string> a(n);

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

    vector<vector<int>> ft(n, vector<int>(m, -1));
    vector<vector<int>> st(n, vector<int>(m, -1));

    queue<tuple<int, int, int>> fr;
    int x1 = -1, y1 = -1;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (a[i][j] == 'X') {
                fr.emplace(i, j, 0);
                ft[i][j] = 0;
            } else if (a[i][j] == 'S') {
                x1 = i;
                y1= j;
            }
        }
    }
    vatra(fr, ft, n, m, a);
    stivaa(x1, y1, ft, st, n, m, a);
    int u = 0;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if ((a[i][j] == '.' || a[i][j] == 'S') && st[i][j] != -1 && 
                (ft[i][j] == -1 || st[i][j] < ft[i][j])) {
                u=u+1;
            }
        }
    }

    cout << u << endl;
    return 0;
}