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

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

struct Point {
    int x, y;
};

bool isInside(int x, int y, int N, int M) {
    return x >= 0 && x < N && y >= 0 && y < M;
}

void spreadFire(queue<Point>& fire, vector<string>& grid, vector<vector<int>>& fireTime, int N, int M) {
    while (!fire.empty()) {
        Point current = fire.front();
        fire.pop();

        for (int d = 0; d < 4; ++d) {
            int nx = current.x + dx[d];
            int ny = current.y + dy[d];

            if (isInside(nx, ny, N, M) && grid[nx][ny] == '.' && fireTime[nx][ny] == -1) {
                fireTime[nx][ny] = fireTime[current.x][current.y] + 1; 
                fire.push({nx, ny});
            }
        }
    }
}

int moveSteva(Point start, vector<string>& grid, vector<vector<int>>& fireTime, int N, int M) {
    queue<Point> steva;
    vector<vector<bool>> visited(N, vector<bool>(M, false));
    int escapeCount = 0;

    steva.push(start);
    visited[start.x][start.y] = true;

    while (!steva.empty()) {
        Point current = steva.front();
        steva.pop();

        for (int d = 0; d < 4; ++d) {
            int nx = current.x + dx[d];
            int ny = current.y + dy[d];

            if (!isInside(nx, ny, N, M)) {
                escapeCount++;
                continue;
            }

            if (grid[nx][ny] == '.' && !visited[nx][ny] &&
                (fireTime[nx][ny] == -1 || fireTime[nx][ny] > fireTime[current.x][current.y] + 1)) {
                visited[nx][ny] = true;
                steva.push({nx, ny});
            }
        }
    }

    return escapeCount;
}
int main() {
    int brvr=0;
    int N, M;
    cin >> N >> M;

    vector<string> grid(N);
    queue<Point> fire;
    vector<vector<int>> fireTime(N, vector<int>(M, -1));
    Point start;

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

    spreadFire(fire, grid, fireTime, N, M);

    int result = moveSteva(start, grid, fireTime, N, M);

    cout << result << endl;

    return 0;
}