#include <iostream>
#include <vector>
#include <queue>
#include <tuple>
#include <limits>
using namespace std;

const int bes = numeric_limits<int>::max();
const int px[] = {-1, 1, 0, 0};
const int py[] = {0, 0, -1, 1};

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

int main() {
    int n, m;
    cin >> n >> m;

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

    queue<pair<int, int>> redV, redS;
    vector<vector<int>> vremeV(n, vector<int>(m, bes));
    vector<vector<int>> vremeS(n, vector<int>(m, bes));
    
    int sx, sy;

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (matrica[i][j] == 'X') {
                redV.push({i, j});
                vremeV[i][j] = 0;
            } else if (matrica[i][j] == 'S') {
                sx = i;
                sy = j;
                redS.push({i, j});
                vremeS[i][j] = 0;
            }
        }
    }
    while (!redV.empty()) {
        int x = redV.front().first;
        int y = redV.front().second;
        redV.pop();
        for (int smer = 0; smer < 4; smer++) {
            int nx = x + px[smer], ny = y + py[smer];
            if (moze(nx, ny, n, m) && matrica[nx][ny] == '.' && vremeV[nx][ny] == bes) {
                vremeV[nx][ny] = vremeV[x][y] + 1;
                redV.push({nx, ny});
            }
        }
    }
    int slobodna = 0;
    while (!redS.empty()) {
        int x = redS.front().first;
        int y = redS.front().second;
        redS.pop();
        for (int smer = 0; smer < 4; smer++) {
            int nx = x + px[smer], ny = y + py[smer];
            if (moze(nx, ny, n, m) && matrica[nx][ny] == '.' && vremeS[nx][ny] == bes) {
                int stigaoS = vremeS[x][y] + 1;
                if (stigaoS < vremeV[nx][ny]) {
                    vremeS[nx][ny] = stigaoS;
                    redS.push({nx, ny});
                }
            }
        }
    }
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (vremeS[i][j] < vremeV[i][j]) {
                slobodna++;
            }
        }
    }

    cout << slobodna << endl;
    return 0;
}