#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
char matrica[1005][1005];
int zaStevu[1005][1005];
int zaVatru[1005][1005];
int redovi[4] = {-1, 0, 1, 0};
int kolone[4] = {0, 1, 0, -1};
queue <pair <int, int>> stevaKoordinate;
queue <pair <int, int>> vatraKoordinate;
int N, M, br = 0;
void bfsVatra(){
    while(!vatraKoordinate.empty()){
        int x = vatraKoordinate.front().first;
        int y = vatraKoordinate.front().second;
        vatraKoordinate.pop();
        for(int i = 0; i < 4; i++){
            int xx = x + redovi[i];
            int yy = y + kolone[i];
            if((matrica[xx][yy] == '.' or matrica[xx][yy] == 'S') and zaVatru[xx][yy] == 0){
                zaVatru[xx][yy] = zaVatru[x][y] + 1;
                vatraKoordinate.push({xx, yy});
            }
        }
    }
}
void bfsSteva(){
    while(!stevaKoordinate.empty()){
        int x = stevaKoordinate.front().first;
        int y = stevaKoordinate.front().second;
        stevaKoordinate.pop();
        for(int i = 0; i < 4; i++){
            int xx = x + redovi[i];
            int yy = y + kolone[i];
            if(matrica[xx][yy] == '.' and zaStevu[xx][yy] == 0){
                zaStevu[xx][yy] = zaStevu[x][y] + 1;
                stevaKoordinate.push({xx, yy});
            }
        }
    }
}
int main(){
    cin >> N >> M;
    memset(zaStevu, 0, sizeof(zaStevu));
    memset(zaVatru, 0, sizeof(zaVatru));
    memset(matrica, '#', sizeof(matrica));
    for(int i = 1; i <= N; i++){
        for(int j = 1; j <= M; j++){
            cin >> matrica[i][j];
            if(matrica[i][j] == 'S'){
                zaStevu[i][j] = 1;
                stevaKoordinate.push({i, j});
            }
            else if(matrica[i][j] == 'X'){
                zaVatru[i][j] = 1;
                vatraKoordinate.push({i, j});
            }
        }
    }
    bfsVatra();
    bfsSteva();
    for(int i = 1; i <= N; i++){
        for(int j = 1; j <= M; j++){
            if (zaStevu[i][j] > 0 and (zaVatru[i][j] == 0 or zaStevu[i][j] < zaVatru[i][j])){
                br++;
            }
        }
    }
    cout << br << endl;
    return 0;
}