#include <bits/stdc++.h>

using namespace std;

const int d[] = {-1, 1, 0, 0};
const int e[] = {0, 0, -1, 1};

bool p(int i, int j, int n, int m) {
    return i >= 0 && i < n && j >= 0 && j < m;
}

int r(int n, int m, vector<string>& h) {
    pair<int, int> x;
    vector<pair<int, int>> y;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (h[i][j] == 'S') x = {i, j};
            else if (h[i][j] == 'X') y.push_back({i, j});
        }
    }

    vector<vector<int>> z(n, vector<int>(m, INT_MAX));
    queue<pair<int, int>> q;

    for (auto& w : y) {
        z[w.first][w.second] = 0;
        q.push(w);
    }

    while (!q.empty()) {
        auto [i, j] = q.front();
        q.pop();

        for (int k = 0; k < 4; k++) {
            int ni = i + d[k];
            int nj = j + e[k];

            if (p(ni, nj, n, m) && h[ni][nj] != '*' && z[ni][nj] == INT_MAX) {
                z[ni][nj] = z[i][j] + 1;
                q.push({ni, nj});
            }
        }
    }

    vector<vector<bool>> w(n, vector<bool>(m, false));
    queue<tuple<int, int, int>> r;
    r.push({x.first, x.second, 0});
    w[x.first][x.second] = true;

    int t = 0;

    while (!r.empty()) {
        auto [i, j, c] = r.front();
        r.pop();

        if (c < z[i][j]) t++;

        for (int k = 0; k < 4; k++) {
            int ni = i + d[k];
            int nj = j + e[k];

            if (p(ni, nj, n, m) && !w[ni][nj] && h[ni][nj] == '.' && c + 1 < z[ni][nj]) {
                w[ni][nj] = true;
                r.push({ni, nj, c + 1});
            }
        }
    }

    return t;
}

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

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

    cout << r(n, m, h) << endl;

    return 0;
}