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

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

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

int main() {
    //freopen("ulaz.txt", "r", stdin);
    //freopen("izlaz.txt", "w", stdout);
    int n, m;
    cin >> n >> m;
    vector<string> lavirint(n);
    vector<vector<int>> vreme_vatre(n, vector<int>(m, beskraj));
    vector<vector<int>> vreme_steve(n, vector<int>(m, beskraj));

    queue<pair<int, int>> vatra;
    pair<int, int> steva_start;

    for (int i = 0; i < n; i++) 
    {
        cin >> lavirint[i];
        for (int j = 0; j < m; j++) 
        {
            if (lavirint[i][j] == 'X') 
            {
                vatra.push({i, j});
                vreme_vatre[i][j] = 0;
            } 
            else if (lavirint[i][j] == 'S') 
            {
                steva_start = {i, j};
                vreme_steve[i][j] = 0;
            }
        }
    }

    while (!vatra.empty()) {
        auto [x, y] = vatra.front();
        vatra.pop();
        for (int d = 0; d < 4; d++) 
        {
            int nx = x + dx[d], ny = y + dy[d];
            if (moguce(nx, ny, n, m) && lavirint[nx][ny] == '.' && 
                vreme_vatre[nx][ny] == beskraj) 
            {
                vreme_vatre[nx][ny] = vreme_vatre[x][y] + 1;
                vatra.push({nx, ny});
            }
        }
    }

    queue<pair<int, int>> steva;
    steva.push(steva_start);

    int br = 0;
    while (!steva.empty()) 
    {
        auto [x, y] = steva.front();
        steva.pop();

        if (vreme_vatre[x][y] > vreme_steve[x][y]) 
        {
            br++;
        }

        for (int d = 0; d < 4; d++) 
        {
            int nx = x + dx[d], ny = y + dy[d];
            if (moguce(nx, ny, n, m) && lavirint[nx][ny] == '.' && 
                vreme_steve[nx][ny] == beskraj) 
            {
                vreme_steve[nx][ny] = vreme_steve[x][y] + 1;
                steva.push({nx, ny});
            }
        }
    }

    cout << br << endl;

    return 0;
}