#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
const int dx[] = {-1, 1, 0, 0};
const int dy[] = {0, 0, -1, 1};

int N, M;
char rud[1000][1000];
int vatra_time[1000][1000];
int stevan_time[1000][1000];

void vatra_bfs(queue<pair<int,int>>&vatra_queue) 
{
    while(!vatra_queue.empty()) {
        int x=vatra_queue.front().first;
        int y=vatra_queue.front().second;
        vatra_queue.pop();
        
        for (int i = 0; i < 4; ++i) 
        {
            int nx=x+dx[i],ny=y+dy[i];
            if(nx>=0 && nx<N && ny>=0 && ny<M && rud[nx][ny]=='.' && vatra_time[nx][ny]==-1) 
            {
                vatra_time[nx][ny]=vatra_time[x][y]+ 1;
                vatra_queue.push({nx, ny});
            }
        }
    }
}

void stevan_bfs(pair<int,int>start) 
{
    queue<pair<int,int>>stevan_queue;
    stevan_queue.push(start);
    stevan_time[start.first][start.second]=0;

    while(!stevan_queue.empty()) 
    {
        int x=stevan_queue.front().first;
        int y=stevan_queue.front().second;
        stevan_queue.pop();

        for(int i=0;i<4;++i) 
        {
            int nx=x+dx[i],ny=y+dy[i];
            if (nx>=0 && nx<N&& ny>=0 && ny<M && rud[nx][ny]=='.' && stevan_time[nx][ny]==-1) 
            {
                stevan_time[nx][ny]=stevan_time[x][y]+ 1;
                stevan_queue.push({nx, ny});
            }
        }
    }
}

int main() 
{
    cin>>N>>M;

    pair<int,int>stevan_start;
    queue<pair<int,int>>vatra_queue;

    memset(vatra_time,-1,sizeof(vatra_time));
    memset(stevan_time,-1,sizeof(stevan_time));

    for(int i=0;i<N;++i) 
    {
        cin>>rud[i];
        for(int j=0;j<M;++j) 
        {
            if(rud[i][j]=='S') 
            {
                stevan_start={i,j}; 
                stevan_time[i][j]=0;
            } 
            else if(rud[i][j]=='X') 
            {
                vatra_queue.push({i,j}); 
                vatra_time[i][j]=0;
            }
        }
    }
    
    vatra_bfs(vatra_queue);
    stevan_bfs(stevan_start);
    
    int result=1;
    for(int i=0;i<N;++i) 
    {
        for(int j=0;j<M;++j) 
        {
            if(rud[i][j]=='.' && stevan_time[i][j]!=-1 && (vatra_time[i][j]==-1 || stevan_time[i][j]<vatra_time[i][j])) 
            {
                result++;
            }
        }
    }

    cout<<result<<endl;
    return 0;
}