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

using namespace std;

const int dx[] = {1, -1, 0, 0};  // Movement directions for up, down, left, right
const int dy[] = {0, 0, 1, -1};

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

    vector<string> matrix(n);
    pair<int, int> stevePos;
    queue<pair<int, int>> fireQueue;
    vector<vector<int>> fireTime(n, vector<int>(m, -1));  // Time when fire reaches a cell
    vector<vector<int>> steveTime(n, vector<int>(m, -1)); // Time when Steva reaches a cell

    for (int i = 0; i < n; i++) {
        cin >> matrix[i];
        for (int j = 0; j < m; j++) {
            if (matrix[i][j] == 'S') {
                stevePos = {i, j};
                steveTime[i][j] = 0;  // Steva starts at time 0
            } else if (matrix[i][j] == 'X') {
                fireQueue.push({i, j});
                fireTime[i][j] = 0;  // Fire starts at time 0
            }
        }
    }

    // BFS for fire spread
    while (!fireQueue.empty()) {
        auto [x, y] = fireQueue.front();
        fireQueue.pop();
        
        for (int i = 0; i < 4; i++) {
            int nx = x + dx[i], ny = y + dy[i];
            if (nx >= 0 && ny >= 0 && nx < n && ny < m && matrix[nx][ny] == '.' && fireTime[nx][ny] == -1) {
                fireTime[nx][ny] = fireTime[x][y] + 1;
                fireQueue.push({nx, ny});
            }
        }
    }

    // BFS for Steva's movement
    queue<pair<int, int>> steveQueue;
    steveQueue.push(stevePos);
    
    while (!steveQueue.empty()) {
        auto [x, y] = steveQueue.front();
        steveQueue.pop();
        
        for (int i = 0; i < 4; i++) {
            int nx = x + dx[i], ny = y + dy[i];
            if (nx >= 0 && ny >= 0 && nx < n && ny < m && matrix[nx][ny] == '.' && steveTime[nx][ny] == -1) {
                steveTime[nx][ny] = steveTime[x][y] + 1;
                steveQueue.push({nx, ny});
            }
        }
    }

    // Count valid escape points
    int validEscapePoints = 0;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (matrix[i][j] == '.' && steveTime[i][j] != -1) {
                // Steva must reach this cell before the fire
                if (fireTime[i][j] == -1 || steveTime[i][j] < fireTime[i][j]) {
                    validEscapePoints++;
                }
            }
        }
    }

    cout << validEscapePoints << endl;

    return 0;
}