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

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

int main() {
    int N, M;
    cin >> N >> M;

    vector<string> maze(N);
    queue<pair<int, int>> fire, steve;
    vector<vector<int>> fireTime(N, vector<int>(M, -1));
    vector<vector<int>> steveTime(N, vector<int>(M, -1));

    for (int i = 0; i < N; i++) {
        cin >> maze[i];
        for (int j = 0; j < M; j++) {
            if (maze[i][j] == 'X') {
                fire.push({i, j});
                fireTime[i][j] = 0;
            } else if (maze[i][j] == 'S') {
                steve.push({i, j});
                steveTime[i][j] = 0;
            }
        }
    }

    while (!fire.empty()) {
        auto [x, y] = fire.front();
        fire.pop();
        for (int dir = 0; dir < 4; dir++) {
            int nx = x + dx[dir], ny = y + dy[dir];
            if (nx >= 0 && nx < N && ny >= 0 && ny < M &&
                fireTime[nx][ny] == -1 && maze[nx][ny] == '.') {
                fireTime[nx][ny] = fireTime[x][y] + 1;
                fire.push({nx, ny});
            }
        }
    }

    int safeCount = 0;
    while (!steve.empty()) {
        auto [x, y] = steve.front();
        steve.pop();
        for (int dir = 0; dir < 4; dir++) {
            int nx = x + dx[dir], ny = y + dy[dir];
            if (nx >= 0 && nx < N && ny >= 0 && ny < M &&
                steveTime[nx][ny] == -1 && maze[nx][ny] == '.') {
                steveTime[nx][ny] = steveTime[x][y] + 1;
                steve.push({nx, ny});
            }
        }
    }

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

    cout << safeCount << endl;
    return 0;
}