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

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

bool uGranici(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_poz;
    vector<pair<int, int>> vatra_poz;

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (lavirint[i][j] == 'S') {
                steva_poz = {i, j};
            } else if (lavirint[i][j] == 'X') {
                vatra_poz.push_back({i, j});
            }
        }
    }

    vector<vector<int>> vreme_vatre(n, vector<int>(m, INT_MAX));
    queue<pair<int, int>> red_vatre;

    for (auto& v : vatra_poz) {
        vreme_vatre[v.first][v.second] = 0;
        red_vatre.push(v);
    }

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

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

            if (uGranici(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_poz.first, steva_poz.second, 0});
    poseceno[steva_poz.first][steva_poz.second] = true;

    int dohvatljiva_polja = 0;

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

        if (vreme < vreme_vatre[x][y]) {
            dohvatljiva_polja++;
        }

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

            if (uGranici(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 dohvatljiva_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;
}