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

const int MAX = 1000;
char grid[MAX][MAX];
bool visitedSteva[MAX][MAX];
bool visitedFire[MAX][MAX];
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};

struct Point {
    int x, y;
};

bool isValid(int x, int y, int n, int m) {
    return x >= 0 && x < n && y >= 0 && y < m && grid[x][y] == '.';
}

int main() {
    int n, m;
    cin >> n >> m;

    queue<Point> fireQueue, stevaQueue;
    int stevaReach = 0;

    // Ucitavanje matrice i inicijalizacija
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            cin >> grid[i][j];
            if (grid[i][j] == 'X') {
                fireQueue.push({i, j});
                visitedFire[i][j] = true;
            } else if (grid[i][j] == 'S') {
                stevaQueue.push({i, j});
                visitedSteva[i][j] = true;
                stevaReach++; // Racunamo pocetnu poziciju
            }
        }
    }

    // Simulacija širenja
    while (!stevaQueue.empty()) {
        // Širenje vatre
        int fireSize = fireQueue.size();
        while (fireSize--) {
            Point fire = fireQueue.front();
            fireQueue.pop();
            for (int d = 0; d < 4; ++d) {
                int nx = fire.x + dx[d];
                int ny = fire.y + dy[d];
                if (isValid(nx, ny, n, m) && !visitedFire[nx][ny]) {
                    visitedFire[nx][ny] = true;
                    grid[nx][ny] = 'X';
                    fireQueue.push({nx, ny});
                }
            }
        }

        // Širenje Steve
        int stevaSize = stevaQueue.size();
        while (stevaSize--) {
            Point steva = stevaQueue.front();
            stevaQueue.pop();
            for (int d = 0; d < 4; ++d) {
                int nx = steva.x + dx[d];
                int ny = steva.y + dy[d];
                if (isValid(nx, ny, n, m) && !visitedSteva[nx][ny] && !visitedFire[nx][ny]) {
                    visitedSteva[nx][ny] = true;
                    stevaReach++;
                    grid[nx][ny] = 'S';
                    stevaQueue.push({nx, ny});
                }
            }
        }
    }

    cout << stevaReach << endl;

    return 0;
}