#include <bits/stdc++.h>
using namespace std;

int N, M;
string lavirint[50];

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

void sirenjevatrebfs(const string lavirint[], int N, int M, int vremevatre[][50]) {
    queue<pair<int, int>> red;

    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            if (lavirint[i][j] == 'X') {
                vremevatre[i][j] = 0;
                red.push({i, j});
            }
        }
    }

    int pravci[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    while (!red.empty()) {
        int x = red.front().first, y = red.front().second;
        red.pop();

        for (auto& pravac : pravci) {
            int nx = x + pravac[0], ny = y + pravac[1];
            if (provera(nx, ny, N, M) && lavirint[nx][ny] == '.' && vremevatre[nx][ny] == -1) {
                vremevatre[nx][ny] = vremevatre[x][y] + 1;
                red.push({nx, ny});
            }
        }
    }
}

void sirenjestevebfs(const string lavirint[], int N, int M, int px, int py, int vremevatre[][50], int vremesteve[][50]) {
    queue<pair<int, int>> red;
    red.push({px, py});
    vremesteve[px][py] = 0;

    int pravci[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    while (!red.empty()) {
        int x = red.front().first, y = red.front().second;
        red.pop();

        for (auto& pravac : pravci) {
            int nx = x + pravac[0], ny = y + pravac[1];
            if (provera(nx, ny, N, M) && lavirint[nx][ny] == '.' && vremesteve[nx][ny] == -1) {

                if (vremevatre[nx][ny] == -1 || vremesteve[x][y] + 1 < vremevatre[nx][ny]) {
                    vremesteve[nx][ny] = vremesteve[x][y] + 1;
                    red.push({nx, ny});
                }
            }
        }
    }
}

int resi(int N, int M, string lavirint[]) {
    int px = -1, py = -1;
    int vremevatre[50][50], vremesteve[50][50];


    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            vremevatre[i][j] = -1;
            vremesteve[i][j] = -1;
        }
    }

    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            if (lavirint[i][j] == 'S') {
                px = i;
                py = j;
                lavirint[i][j] = '.';
            }
        }
    }


    sirenjevatrebfs(lavirint, N, M, vremevatre);
    sirenjestevebfs(lavirint, N, M, px, py, vremevatre, vremesteve);

    int brojizlaza = 0;


    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            if (lavirint[i][j] == '.' && vremesteve[i][j] != -1 && (vremevatre[i][j] == -1 || vremesteve[i][j] < vremevatre[i][j])) {
                brojizlaza++;
            }
        }
    }

    return brojizlaza;
}

int main() {
    cin >> N >> M;
    for (int i = 0; i < N; i++) {
        cin >> lavirint[i];
    }

    cout << resi(N, M, lavirint) << endl;

    return 0;
}