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

using namespace std;

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

int main() {
    int n, m;
    cin >> n >> m;
    vector<string> grid(n);

    queue<pair<int, int>> fireQueue; 
    vector<vector<int>> fireTime(n, vector<int>(m, INT_MAX)); 
    pair<int, int> stevaPos; 

    for (int i = 0; i < n; ++i) {
        cin >> grid[i];
        for (int j = 0; j < m; ++j) {
            if (grid[i][j] == 'X') {
                fireQueue.push({i, j});
                fireTime[i][j] = 0; 
            } else if (grid[i][j] == 'S') {
                stevaPos = {i, j};
            }
        }
    }

    while (!fireQueue.empty()) {
        auto cell = fireQueue.front();
        fireQueue.pop();
        int x = cell.first, y = cell.second;

        for (int d = 0; d < 4; ++d) {
            int nx = x + dx[d], ny = y + dy[d];
            if (nx >= 0 && nx < n && ny >= 0 && ny < m && grid[nx][ny] == '.' && fireTime[nx][ny] == INT_MAX) {
                fireTime[nx][ny] = fireTime[x][y] + 1;
                fireQueue.push({nx, ny});
            }
        }
    }

    queue<pair<int, int>> stevaQueue;
    vector<vector<int>> stevaTime(n, vector<int>(m, INT_MAX));
    stevaQueue.push(stevaPos);
    stevaTime[stevaPos.first][stevaPos.second] = 0;

    int safeCells = 0;

    while (!stevaQueue.empty()) {
        auto cell = stevaQueue.front();
        stevaQueue.pop();
        int x = cell.first, y = cell.second;

        if (stevaTime[x][y] < fireTime[x][y]) safeCells++;
        

        for (int d = 0; d < 4; ++d) {
            int nx = x + dx[d], ny = y + dy[d];
            if (nx >= 0 && nx < n && ny >= 0 && ny < m && grid[nx][ny] == '.' && stevaTime[nx][ny] == INT_MAX) {
                int newTime = stevaTime[x][y] + 1;
                if (newTime < fireTime[nx][ny]) {
                    stevaTime[nx][ny] = newTime;
                    stevaQueue.push({nx, ny});
                }
            }
        }
    }

    cout << safeCells;

    return 0;
}