#include <bits/stdc++.h>

using namespace std;

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

bool v(int x, int y, int n, int m) {
    return x >= 0 && x < n && y >= 0 && y < m;
}

int s(int n, int m, vector<string>& g) {
    pair<int, int> a;
    vector<pair<int, int>> b;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (g[i][j] == 'S') a = {i, j};
            else if (g[i][j] == 'X') b.push_back({i, j});
        }
    }

    vector<vector<int>> c(n, vector<int>(m, INT_MAX));
    queue<pair<int, int>> d;

    for (auto& e : b) {
        c[e.first][e.second] = 0;
        d.push(e);
    }

    while (!d.empty()) {
        auto [x, y] = d.front();
        d.pop();

        for (int i = 0; i < 4; i++) {
            int nx = x + dx[i];
            int ny = y + dy[i];

            if (v(nx, ny, n, m) && g[nx][ny] != '*' && c[nx][ny] == INT_MAX) {
                c[nx][ny] = c[x][y] + 1;
                d.push({nx, ny});
            }
        }
    }

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

    int t = 0;

    while (!e.empty()) {
        auto [x, y, z] = e.front();
        e.pop();

        if (z < c[x][y]) t++;

        for (int i = 0; i < 4; i++) {
            int nx = x + dx[i];
            int ny = y + dy[i];

            if (v(nx, ny, n, m) && !f[nx][ny] && g[nx][ny] == '.' && z + 1 < c[nx][ny]) {
                f[nx][ny] = true;
                e.push({nx, ny, z + 1});
            }
        }
    }

    return t;
}

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

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

    cout << s(n, m, g) << endl;

    return 0;
}