#include <iostream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;

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

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

int main() {
    int n, m;
    cin >> n >> m;
    vector<string> l(n);
    for (int i = 0; i < n; i++) {
        cin >> l[i];
    }
    vector<vector<int>> vv(n, vector<int>(m, INT_MAX));
    vector<vector<int>> sv(n, vector<int>(m, -1));
    queue<pair<int, int>> vr;
    pair<int, int> sp;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (l[i][j] == 'X') {
                vr.push({i, j});
                vv[i][j] = 0;
            } else if (l[i][j] == 'S') {
                sp = {i, j};
            }
        }
    }
    while (!vr.empty()) {
        auto [x, y] = vr.front();
        vr.pop();
        for (int dir = 0; dir < 4; dir++) {
            int nx = x + dx[dir], ny = y + dy[dir];
            if (dp(nx, ny, n, m) && l[nx][ny] != '*' && vv[nx][ny] == INT_MAX) {
                vv[nx][ny] = vv[x][y] + 1;
                vr.push({nx, ny});
            }
        }
    }
    queue<pair<int, int>> sr;
    sr.push(sp);
    sv[sp.first][sp.second] = 0;
    int result = 0;
    while (!sr.empty()) {
        auto [x, y] = sr.front();
        sr.pop();
        if (sv[x][y] < vv[x][y]) {
            result++;
        }
        for (int dir = 0; dir < 4; dir++) {
            int nx = x + dx[dir], ny = y + dy[dir];
            if (dp(nx, ny, n, m) && l[nx][ny] != '*' && sv[nx][ny] == -1) {
                if (sv[x][y] + 1 < vv[nx][ny]) {
                    sv[nx][ny] = sv[x][y] + 1;
                    sr.push({nx, ny});
                }
            }
        }
    }
    cout << result << endl;
    return 0;
}