#include <bits/stdc++.h>
using namespace std;
struct mesto_vreme{
    int x,y,time;
};
int n,m;
const int dx[]={-1,0,1,0};
const int dy[]={0,1,0,-1};
char lavirint[1005][1005];
queue<mesto_vreme> vatraMesto;
mesto_vreme steva;

bool more(int x,int y){
    return (x>=0 and x<n and y>=0 and y<m and lavirint[x][y]!='*');
}

vector<vector<int>> sirenjeVatra(){
    vector<vector<int>> vatraT(n, vector<int>(m, 1e9));
    for (int i=0;i<n;i++){
        for (int j=0;j<m;j++){
            if (lavirint[i][j]=='X'){
                vatraT[i][j]=0;
                vatraMesto.push({i,j,0});
            }
        }
    }

    while(vatraMesto.size()){
        mesto_vreme curr=vatraMesto.front();
        vatraMesto.pop();
        for (int i=0;i<4;i++){
            int nx=curr.x+dx[i];
            int ny=curr.y+dy[i];
            if (more(nx,ny) and vatraT[nx][ny]==1e9){
                vatraT[nx][ny]=curr.time+1;
                vatraMesto.push({nx,ny,curr.time+1});
            }
        }
    }

    return vatraT;
}


int resi(){
    int skor=0;
    vector<vector<bool>> idx(n, vector<bool>(m,false));
    vector<vector<int>> vatraT=sirenjeVatra();
    queue<mesto_vreme> stevaProlazi;
    stevaProlazi.push(steva);
    idx[steva.x][steva.y]=true;

    while(stevaProlazi.size()){
        mesto_vreme curr=stevaProlazi.front();
        stevaProlazi.pop();
        if (curr.time<vatraT[curr.x][curr.y]){
            skor++;
            for (int i=0;i<4;i++){
                int nx=curr.x+dx[i];
                int ny=curr.y+dy[i];
                if (more(nx,ny) and idx[nx][ny]!=true){
                    idx[nx][ny]=true;
                    stevaProlazi.push({nx,ny,curr.time+1});
                }
            }
        }
    }
    return skor;
}


int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    scanf("%d%d",&n,&m);
    for (int i=0;i<n;i++){
        for (int j=0;j<m;j++){
            cin >> lavirint[i][j];
            if(lavirint[i][j]=='S'){
                steva = {i,j,0};
            }
        }
    }
//    printf("%d %d %d\n",steva.x,steva.y,steva.time);
    printf("%d\n",resi());
    return 0;
}
/*
6 4
.S..
*.**
..**
....
.***
X...

*/