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

using namespace std;

int N, M;
vector<vector<char>> labirint;
vector<vector<int>> fireTime, stevaTime;
queue<pair<int, int>> fireQueue, stevaQueue;

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

void fireBFS() {
    while (!fireQueue.empty()) {
        pair<int, int> current = fireQueue.front();
        fireQueue.pop();

        int x = current.first, y = current.second;
        for (auto& dir : directions) {
            int nx = x + dir[0], ny = y + dir[1];
            if (nx >= 0 && nx < N && ny >= 0 && ny < M && labirint[nx][ny] == '.' && fireTime[nx][ny] == -1) {
                fireTime[nx][ny] = fireTime[x][y] + 1;
                fireQueue.push({ nx, ny });
            }
        }
    }
}

void stevaBFS() {
    while (!stevaQueue.empty()) {
        pair<int, int> current = stevaQueue.front();
        stevaQueue.pop();

        int x = current.first, y = current.second;
        for (auto& dir : directions) {
            int nx = x + dir[0], ny = y + dir[1];
            if (nx >= 0 && nx < N && ny >= 0 && ny < M && labirint[nx][ny] == '.' && stevaTime[nx][ny] == -1) {
                stevaTime[nx][ny] = stevaTime[x][y] + 1;
                stevaQueue.push({ nx, ny });
            }
        }
    }
}

int main() {
    cin >> N >> M;
    labirint.resize(N, vector<char>(M));
    fireTime.assign(N, vector<int>(M, -1));
    stevaTime.assign(N, vector<int>(M, -1));

    int startX = -1, startY = -1;

    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < M; ++j) {
            cin >> labirint[i][j];
            if (labirint[i][j] == 'X') {
                fireQueue.push({ i, j });
                fireTime[i][j] = 0;
            }
            if (labirint[i][j] == 'S') {
                startX = i;
                startY = j;
            }
        }
    }

    fireBFS();

    stevaQueue.push({ startX, startY });
    stevaTime[startX][startY] = 0;
    stevaBFS();

    int validFields = 0;
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < M; ++j) {
            if (labirint[i][j] == '.' && stevaTime[i][j] != -1) {
                if (fireTime[i][j] == -1 || stevaTime[i][j] <= fireTime[i][j]) {
                    ++validFields;
                }
            }
        }
    }

    if (labirint[startX][startY] == '.' && fireTime[startX][startY] == -1) {
        validFields++;
    }

    cout << validFields + 1 << endl;
    return 0;
}