#include <iostream>
#include <queue>
#include <vector>
#include <cstring>

using namespace std;

int pravci[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

void vatra(const vector<string>& a, vector<vector<int>>& vatravrm, int N, int M)
{
    queue<pair<int, int>> q;
    for (int i = 0; i < N; i++)
        {
        for (int j = 0; j < M; j++)
        {
            if (a[i][j] == 'X')
                {
                vatravrm[i][j] = 0;
                q.push({i, j});
            }
        }
    }

    while (!q.empty())
        {
        auto [x, y] = q.front();
        q.pop();
        for (auto [dx, dy] : pravci)
            {
            int nx = x + dx, ny = y + dy;
            if (nx >= 0 && nx < N && ny >= 0 && ny < M && a[nx][ny] == '.' && vatravrm[nx][ny] == -1)
                {
                vatravrm[nx][ny] = vatravrm[x][y] + 1;
                q.push({nx, ny});
            }
        }
    }
}
void steva(const vector<string>& a, int start_x, int start_y, const vector<vector<int>>& vatravrm, vector<vector<int>>& stvrm, int N, int M) {
    queue<pair<int, int>> q;
    q.push({start_x, start_y});
    stvrm[start_x][start_y] = 0;
    while (!q.empty())
        {
        auto [x, y] = q.front();
        q.pop();
        for (auto [dx, dy] : pravci)
            {
            int nx = x + dx, ny = y + dy;
            if (nx >= 0 && nx < N && ny >= 0 && ny < M && a[nx][ny] == '.' && stvrm[nx][ny] == -1)
            {
                if (vatravrm[nx][ny] == -1 || stvrm[x][y] + 1 < vatravrm[nx][ny])
                {
                    stvrm[nx][ny] = stvrm[x][y] + 1;
                    q.push({nx, ny});
                }
            }
        }
    }
}

int solve(int N, int M, vector<string>& a)
{
    vector<vector<int>> vatravrm(N, vector<int>(M, -1));
    int start_x = -1, start_y = -1;
    for (int i = 0; i < N; i++)
        {
        for (int j = 0; j < M; j++)
        {
            if (a[i][j] == 'S')
            {
                start_x = i;
                start_y = j;
                a[i][j] = '.';
                break;
            }
        }
    }
    vatra(a, vatravrm, N, M);
    vector<vector<int>> stvrm(N, vector<int>(M, -1));
    steva(a, start_x, start_y, vatravrm, stvrm, N, M);
    int br = 0;
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            if (a[i][j] == '.' && stvrm[i][j] != -1 && (vatravrm[i][j] == -1 || stvrm[i][j] < vatravrm[i][j])) {
                br++;
            }
        }
    }
    return br;
}

int main() {
    int N, M;
    cin >> N >> M;
    vector<string> a(N);
    for (int i = 0; i < N; i++) {
        cin >> a[i];
    }
    cout << solve(N, M, a) << endl;

    return 0;
}