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

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

bool isValid(int x, int y, int N, int M) {
    return x >= 0 && x < N && y >= 0 && y < M;
}

int resiLavirint(int N, int M, vector<string>& lavirint) {
    pair<int, int> steva;
    vector<pair<int, int>> vatre;

    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            if (lavirint[i][j] == 'S') {
                steva = {i, j};
            } else if (lavirint[i][j] == 'X') {
                vatre.push_back({i, j});
            }
        }
    }
    vector<vector<int>> vreme_vatre(N, vector<int>(M, INT_MAX));
    queue<pair<int, int>> red_vatre;
    for (auto& vatra : vatre) {
        vreme_vatre[vatra.first][vatra.second] = 0;
        red_vatre.push(vatra);
    }

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

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

            if (isValid(nx, ny, N, M) && lavirint[nx][ny] != '*' && vreme_vatre[nx][ny] == INT_MAX) {
                vreme_vatre[nx][ny] = vreme_vatre[x][y] + 1;
                red_vatre.push({nx, ny});
            }
        }
    }
    vector<vector<bool>> poseceno(N, vector<bool>(M, false));
    queue<tuple<int, int, int>> red_steve;
    red_steve.push({steva.first, steva.second, 0});
    poseceno[steva.first][steva.second] = true;
    int dostupna_polja = 0;
    while (!red_steve.empty()) {
        auto [x, y, vreme] = red_steve.front();
        red_steve.pop();

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

            if (isValid(nx, ny, N, M) && !poseceno[nx][ny] && lavirint[nx][ny] == '.' && vreme + 1 < vreme_vatre[nx][ny]) {
                poseceno[nx][ny] = true;
                red_steve.push({nx, ny, vreme + 1});
            }
        }
    }
    return dostupna_polja;
}
int main() {
    int N, M;
    cin >> N >> M;

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

    cout << resiLavirint(N, M, lavirint) << endl;

    return 0;
}