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

#define MAX_N 1000
#define INF 1000000000

int N, M;
char labyrinth[MAX_N][MAX_N];
int fire_time[MAX_N][MAX_N];
int steva_time[MAX_N][MAX_N];

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


void bfs(int start_x, int start_y, int time[MAX_N][MAX_N]) {
    int queue[MAX_N * MAX_N][2], front = 0, rear = 0;
    time[start_x][start_y] = 0;
    queue[rear][0] = start_x; queue[rear][1] = start_y; rear++;

    while (front < rear) {
        int x = queue[front][0], y = queue[front][1]; front++;
        for (int i = 0; i < 4; i++) {
            int nx = x + directions[i][0], ny = y + directions[i][1];
            if (nx >= 0 && ny >= 0 && nx < N && ny < M && labyrinth[nx][ny] != '*' && time[nx][ny] == INF) {
                time[nx][ny] = time[x][y] + 1;
                queue[rear][0] = nx; queue[rear][1] = ny; rear++;
            }
        }
    }
}

int main() {
    
    scanf("%d %d", &N, &M);
    for (int i = 0; i < N; i++) {
        scanf("%s", labyrinth[i]);
    }

    
    memset(fire_time, INF, sizeof(fire_time));
    memset(steva_time, INF, sizeof(steva_time));

    int start_steva_x = -1, start_steva_y = -1;
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            if (labyrinth[i][j] == 'S') {
                start_steva_x = i; start_steva_y = j;
            }
            if (labyrinth[i][j] == 'X') {
                fire_time[i][j] = 0;
            }
        }
    }

    
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            if (fire_time[i][j] == 0) {
                bfs(i, j, fire_time);
            }
        }
    }

    
    bfs(start_steva_x, start_steva_y, steva_time);

    
    int count = 0;
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            if ((labyrinth[i][j] == '.' || labyrinth[i][j] == 'S') && steva_time[i][j] < fire_time[i][j]) {
                count++;
            }
        }
    }

    printf("%d\n", count);
    return 0;
}