#include <stdio.h>
#include <stdlib.h>
#include <queue>
#include <string.h>

#define MAX_N 1000
#define MAX_M 1000


typedef struct {
    int x, y;
} Point;


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


int fire_time[MAX_N][MAX_M];
int steve_time[MAX_N][MAX_M];


char maze[MAX_N][MAX_M];

int N, M;


void bfs_fire(Point fire_starts[], int num_fire) {
    std::queue<Point> q;
    
  
    for (int i = 0; i < num_fire; i++) {
        q.push(fire_starts[i]);
        fire_time[fire_starts[i].x][fire_starts[i].y] = 0;
    }
    
    while (!q.empty()) {
        Point p = q.front();
        q.pop();
        
        
        for (int i = 0; i < 4; i++) {
            int nx = p.x + dx[i];
            int ny = p.y + dy[i];
            
            if (nx >= 0 && nx < N && ny >= 0 && ny < M && maze[nx][ny] == '.' && fire_time[nx][ny] == -1) {
                fire_time[nx][ny] = fire_time[p.x][p.y] + 1;
                q.push((Point){nx, ny});
            }
        }
    }
}


void bfs_steve(Point start) {
    std::queue<Point> q;
    q.push(start);
    steve_time[start.x][start.y] = 0;
    
    while (!q.empty()) {
        Point p = q.front();
        q.pop();
        
        
        for (int i = 0; i < 4; i++) {
            int nx = p.x + dx[i];
            int ny = p.y + dy[i];
            
            if (nx >= 0 && nx < N && ny >= 0 && ny < M && maze[nx][ny] == '.' && steve_time[nx][ny] == -1) {
            
                if (fire_time[nx][ny] == -1 || steve_time[p.x][p.y] + 1 < fire_time[nx][ny]) {
                    steve_time[nx][ny] = steve_time[p.x][p.y] + 1;
                    q.push((Point){nx, ny});
                }
            }
        }
    }
}

int main() {
 
    scanf("%d %d", &N, &M);
    
  
    Point fire_starts[MAX_N * MAX_M];
    int num_fire = 0;
    Point steve_start;
    

    memset(fire_time, -1, sizeof(fire_time));
    memset(steve_time, -1, sizeof(steve_time));
    
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            scanf(" %c", &maze[i][j]);
            
            if (maze[i][j] == 'X') {
                fire_starts[num_fire++] = (Point){i, j};
            }
            if (maze[i][j] == 'S') {
                steve_start = (Point){i, j};
            }
        }
    }
    
    bfs_fire(fire_starts, num_fire);
    
  
    bfs_steve(steve_start);
    

    int result = 0;
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            
            if (maze[i][j] == '.' && steve_time[i][j] != -1 && (fire_time[i][j] == -1 || steve_time[i][j] < fire_time[i][j])) {
                result++;
            }
        }
    }
    
    
    printf("%d\n", result);
    
    return 0;
}