#include <iostream>
#include <queue>
#include <vector>

using namespace std;


int dirs[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};


bool isValid(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>> maze(N, vector<char>(M));
    vector<vector<int>> fireTime(N, vector<int>(M, -1)); 
    vector<vector<int>> steveTime(N, vector<int>(M, -1)); 

    queue<pair<int, int>> fireQueue; 
    queue<pair<int, int>> steveQueue; 
    pair<int, int> steveStart; 

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

    
    while (!fireQueue.empty()) {
        int x = fireQueue.front().first;
        int y = fireQueue.front().second;
        fireQueue.pop();

        
        for (int i = 0; i < 4; i++) {
            int nx = x + dirs[i][0];
            int ny = y + dirs[i][1];

            
            if (isValid(nx, ny, N, M) && fireTime[nx][ny] == -1 && maze[nx][ny] != '*') {
                fireTime[nx][ny] = fireTime[x][y] + 1; 
                fireQueue.push({nx, ny});
            }
        }
    }

    
    while (!steveQueue.empty()) {
        int x = steveQueue.front().first;
        int y = steveQueue.front().second;
        steveQueue.pop();

        
        for (int i = 0; i < 4; i++) {
            int nx = x + dirs[i][0];
            int ny = y + dirs[i][1];

            
            if (isValid(nx, ny, N, M) && steveTime[nx][ny] == -1 && maze[nx][ny] != '*') {
                
                if (fireTime[nx][ny] == -1 || fireTime[nx][ny] > steveTime[x][y] + 1) {
                    steveTime[nx][ny] = steveTime[x][y] + 1;
                    steveQueue.push({nx, ny});
                }
            }
        }
    }

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

    cout << count << endl;

    return 0;
}