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

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

int N, M;
char mapa[MAXN][MAXN];
int fire_dist[MAXN][MAXN];   
int steve_dist[MAXN][MAXN]; 



bool provera(int x, int y) {
    return x >= 0 && x < N && y >= 0 && y < M && mapa[x][y] != '*';
}

void bfs_fire() {
    queue<pair<int, int>> q;
    memset(fire_dist, -1, sizeof(fire_dist));
    
    for(int i = 0; i < N; i++) {
        for(int j = 0; j < M; j++) {
            if(mapa[i][j] == 'X') {
                q.push(make_pair(i, j));
                fire_dist[i][j] = 0;
            }
        }
    }
    
    while(!q.empty()) {
        int x = q.front().first;
        int y = q.front().second;
        q.pop();
        
        for(int d = 0; d < 4; d++) {
            int nx = x + dx[d];
            int ny = y + dy[d];
            
            if(provera(nx, ny) && fire_dist[nx][ny] == -1) {
                fire_dist[nx][ny] = fire_dist[x][y] + 1;
                q.push(make_pair(nx, ny));
            }
        }
    }
}

void bfs_steve(int start_x, int start_y) {
    queue<pair<int, int>> q;
    memset(steve_dist, -1, sizeof(steve_dist));
    
    q.push(make_pair(start_x, start_y));
    steve_dist[start_x][start_y] = 0;
    
    while(!q.empty()) {
        int x = q.front().first;
        int y = q.front().second;
        q.pop();
        
        for(int d = 0; d < 4; d++) {
            int nx = x + dx[d];
            int ny = y + dy[d];
            
            if(provera(nx, ny) && steve_dist[nx][ny] == -1) {
                if(fire_dist[nx][ny] == -1 || steve_dist[x][y] + 1 < fire_dist[nx][ny]) {
                    steve_dist[nx][ny] = steve_dist[x][y] + 1;
                    q.push(make_pair(nx, ny));
                }
            }
        }
    }
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    
    cin >> N >> M;
    
    int steve_x, steve_y;
    for(int i = 0; i < N; i++) {
        for(int j = 0; j < M; j++) {
            cin >> mapa[i][j];
            if(mapa[i][j] == 'S') {
                steve_x = i;
                steve_y = j;
            }
        }
    }
    
    bfs_fire();
    bfs_steve(steve_x, steve_y);
    
    int resenje = 0;
    for(int i = 0; i < N; i++) {
        for(int j = 0; j < M; j++) {
            if(steve_dist[i][j] != -1 ) resenje++;
        }
    }
    
    cout << resenje << "\n";
    
    return 0;
}