#include <iostream>
#include <cstring>
using namespace std;

const int maxn = 1000;
const int maxm = 1000;
const int dx[4] = {-1, 1, 0, 0};
const int dy[4] = {0, 0, -1, 1};

int N, M;
char l[maxn][maxm];
int vv[maxn][maxm];
int vs[maxn][maxm];

void vatra() {
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            if (l[i][j] == 'X')
            {
                vv[i][j] = 0;
            } 
            else
            {
                vv[i][j] = -1;
            }
        }
    }
    bool promena = true;
    while (promena)
    {
        promena = false;
        for (int i = 0; i < N; i++)
        {
            for (int j = 0; j < M; j++) 
            {
                if (vv[i][j] != -1) 
                {
                    for (int dir = 0; dir < 4; dir++) 
                    {
                        int nx = i + dx[dir];
                        int ny = j + dy[dir];

                        if (nx >= 0 && nx < N && ny >= 0 && ny < M && l[nx][ny] == '.' && vv[nx][ny] == -1) 
                        {
                            vv[nx][ny] = vv[i][j] + 1;
                            promena = true;
                        }
                    }
                }
            }
        }
    }
}
void steva(int px, int py) 
{
    for (int i = 0; i < N; i++) 
    {
        for (int j = 0; j < M; j++)
        {
            vs[i][j] = -1;
        }
    }
    vs[px][py] = 0;
    bool promena1 = true;
    while (promena1) 
    {
        promena1 = false;
        for (int i = 0; i < N; i++) 
        {
            for (int j = 0; j < M; j++) 
            {
                if (vs[i][j] != -1) 
                {
                    for (int dir = 0; dir < 4; dir++) 
                    {
                        int nx = i + dx[dir];
                        int ny = j + dy[dir];

                        if (nx >= 0 && nx < N && ny >= 0 && ny < M && l[nx][ny] == '.' && vs[nx][ny] == -1) 
                        {
                            if (vv[nx][ny] == -1 || vs[i][j] + 1 < vv[nx][ny]) 
                            {
                                vs[nx][ny] = vs[i][j] + 1;
                                promena1 = true;
                            }
                        }
                    }
                }
            }
        }
    }
}
int main() {
    cin >> N >> M;
    int pocetnax, pocetnay;
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            cin >> l[i][j];
            if (l[i][j] == 'S') 
            {
                pocetnax = i;
                pocetnay = j;
            }
        }
    }
    vatra();
    steva(pocetnax, pocetnay);
    int resenje = 0;
    for (int i = 0; i < N; i++) 
    {
        for (int j = 0; j < M; j++) 
        {
            if (l[i][j] == '.' && vs[i][j] != -1 && (vv[i][j] == -1 || vs[i][j] < vv[i][j])) 
            {
            resenje++;
            }
        }
    }

    cout << resenje + 1 << endl;

    return 0;
}