#include <iostream>
#include <vector>
#include <queue>
#include <set>

using namespace std;

struct Point {
    int x, y;
};

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

void prosiriVatru(int N, int M, vector<string>& matrica, vector<vector<int>>& vatraVreme, queue<Point>& vatraQueue) {
    while (!vatraQueue.empty()) {
        Point p = vatraQueue.front();
        vatraQueue.pop();

        for (int i = 0; i < 4; ++i) {
            int nx = p.x + dx[i], ny = p.y + dy[i];
            if (nx >= 0 && nx < N && ny >= 0 && ny < M && matrica[nx][ny] == '.' && vatraVreme[nx][ny] == -1) {
                vatraVreme[nx][ny] = vatraVreme[p.x][p.y] + 1;
                vatraQueue.push({ nx, ny });
            }
        }
    }
}

void kretanjeSteve(int N, int M, vector<string>& matrica, vector<vector<int>>& stevaVreme, queue<Point>& stevaQueue, vector<vector<int>>& vatraVreme) {
    while (!stevaQueue.empty()) {
        Point p = stevaQueue.front();
        stevaQueue.pop();

        for (int i = 0; i < 4; ++i) {
            int nx = p.x + dx[i], ny = p.y + dy[i];
            if (nx >= 0 && nx < N && ny >= 0 && ny < M && matrica[nx][ny] == '.' && stevaVreme[nx][ny] == -1) {
                if (vatraVreme[nx][ny] == -1 || stevaVreme[p.x][p.y] + 1 < vatraVreme[nx][ny]) {
                    stevaVreme[nx][ny] = stevaVreme[p.x][p.y] + 1;
                    stevaQueue.push({ nx, ny });
                }
            }
        }
    }
}

int main() {
    int N, M;
    cin >> N >> M;

    vector<string> matrica(N);
    Point steva;
    vector<Point> vatra;

    for (int i = 0; i < N; ++i) {
        cin >> matrica[i];
        for (int j = 0; j < M; ++j) {
            if (matrica[i][j] == 'S') {
                steva = { i, j };
            }
            else if (matrica[i][j] == 'X') {
                vatra.push_back({ i, j });
            }
        }
    }

    vector<vector<int>> vatraVreme(N, vector<int>(M, -1));
    queue<Point> vatraQueue;

    for (const auto& p : vatra) {
        vatraVreme[p.x][p.y] = 0;
        vatraQueue.push(p);
    }

    prosiriVatru(N, M, matrica, vatraVreme, vatraQueue);

    vector<vector<int>> stevaVreme(N, vector<int>(M, -1));
    queue<Point> stevaQueue;
    stevaQueue.push(steva);
    stevaVreme[steva.x][steva.y] = 0;

    kretanjeSteve(N, M, matrica, stevaVreme, stevaQueue, vatraVreme);

    set<pair<int, int>> poljaSaKojiimaSeStevaKretala; 
    int count = 0;

    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < M; ++j) {
            if (matrica[i][j] == '.' || matrica[i][j] == 'S') {
                if (stevaVreme[i][j] != -1 && (vatraVreme[i][j] == -1 || stevaVreme[i][j] < vatraVreme[i][j])) {
                    poljaSaKojiimaSeStevaKretala.insert({ i, j });
                }
            }
        }
    }

    count = poljaSaKojiimaSeStevaKretala.size();
    cout << count << endl;

    return 0;
}