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

using namespace std;

int N, M;
vector<vector<char>> matrix;
vector<vector<int>> fireTime, steveTime;

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

bool isValid(int x, int y) {
    return x >= 0 && x < N && y >= 0 && y < M && matrix[x][y] != '*';
}

void bfsFire() {
    queue<pair<int, int>> fireQueue;

    fireTime.assign(N, vector<int>(M, -1));

    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            if (matrix[i][j] == 'X') {
                fireQueue.push({i, j});
                fireTime[i][j] = 0;
            }
        }
    }

    while (!fireQueue.empty()) {
        auto [x, y] = fireQueue.front();
        fireQueue.pop();

        for (auto [dx, dy] : directions) {
            int nx = x + dx, ny = y + dy;
            if (isValid(nx, ny) && fireTime[nx][ny] == -1) {
                fireTime[nx][ny] = fireTime[x][y] + 1;
                fireQueue.push({nx, ny});
            }
        }
    }
}

void bfsSteve(pair<int, int> start) {
    queue<pair<int, int>> steveQueue;

    steveTime.assign(N, vector<int>(M, -1));

    int sx = start.first, sy = start.second;
    steveQueue.push({sx, sy});
    steveTime[sx][sy] = 0;

    while (!steveQueue.empty()) {
        auto [x, y] = steveQueue.front();
        steveQueue.pop();

        for (auto [dx, dy] : directions) {
            int nx = x + dx, ny = y + dy;
            if (isValid(nx, ny) && steveTime[nx][ny] == -1) {
                if (fireTime[nx][ny] == -1 || fireTime[nx][ny] > steveTime[x][y] + 1) {
                    steveTime[nx][ny] = steveTime[x][y] + 1;
                    steveQueue.push({nx, ny});
                }
            }
        }
    }
}

int countReachableCells() {
    int reachableCount = 0;

    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            if (matrix[i][j] == '.' || matrix[i][j] == 'S') {
                if (steveTime[i][j] != -1 && (fireTime[i][j] == -1 || steveTime[i][j] < fireTime[i][j])) {
                    reachableCount++;
                }
            }
        }
    }

    return reachableCount;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    cin >> N >> M;
    matrix.resize(N, vector<char>(M));

    pair<int, int> steveStart;

    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            cin >> matrix[i][j];
            if (matrix[i][j] == 'S') {
                steveStart = {i, j};
            }
        }
    }

    bfsFire();

    bfsSteve(steveStart);

    cout << countReachableCells() << endl;

    return 0;
}