#include <bits/stdc++.h>

using namespace std;


struct Tacka { int x, y; }; 

const vector<Tacka> smerovi = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; 

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

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

    vector<vector<char>> lavirint(n, vector<char>(m)); 
    queue<Tacka> prviRed, stevaRed; 

    Tacka stevaStart; 


    for (int i = 0; i < n; i++) { 
        for (int j = 0; j < m; j++) { 
            cin >> lavirint[i][j]; 
            if (lavirint[i][j] == 'X') { 
                prviRed.push({i, j}); 
                } else if (lavirint[i][j] == 'S') { 
                    stevaStart = {i, j}; stevaRed.push(stevaStart); 
                } 
            } 
        } 
    vector<vector<int>> fireTime(n, vector<int>(m, -1)); 
    vector<vector<int>> stevaTime(n, vector<int>(m, -1)); 
    int time = 0; 
    
    while (!prviRed.empty()) 
    { int size = prviRed.size(); 
    for (int i = 0; i < size; i++) { 
        Tacka p = prviRed.front(); 
        prviRed.pop(); 
        fireTime[p.x][p.y] = time; 
        for (const auto& dir : smerovi) { 
            int nx = p.x + dir.x; 
            int ny = p.y + dir.y; 
            if (validacija(nx, ny, n, m) && lavirint[nx][ny] == '.' && fireTime[nx][ny] == -1) { 
                prviRed.push({nx, ny}); fireTime[nx][ny] = time + 1; 
                } 
            } 
        } 
    ++time; 
    } 

    time = 0; 
    stevaTime[stevaStart.x][stevaStart.y] = 0; 
    int escapeCells = 1; 
    while (!stevaRed.empty()) { 
        int size = stevaRed.size(); 
        for (int i = 0; i < size; i++) { 
            Tacka p = stevaRed.front(); 
            stevaRed.pop(); 
            for (const auto& dir : smerovi) { 
                int nx = p.x + dir.x; int ny = p.y + dir.y; 
                if (validacija(nx, ny, n, m) && lavirint[nx][ny] == '.' && stevaTime[nx][ny] == -1) { 
                    stevaRed.push({nx, ny}); 
                    stevaTime[nx][ny] = time + 1;
                    if (fireTime[nx][ny] == -1 || fireTime[nx][ny] > stevaTime[nx][ny]) { 
                        escapeCells++; 
                        } 
                    } 
                } 
            } 
            time++; 
        } 
    cout << escapeCells << endl; 
    return 0;

}