#include <bits/stdc++.h>
#define ll long long
#define first f
#define second s
using namespace std;

const int MAXN = 1e3 + 5;
int N, M, di[] = {1, 0, -1, 0}, dj[] = {0, 1, 0, -1};
char C[MAXN][MAXN];
int A[MAXN][MAXN], sol;
struct q
{
    int i, j, t;
};
queue<q> Q;
void BFS()
{
    int qi, qj, qt;
    while(Q.size())
    {
        qi = Q.front().i;
        qj = Q.front().j;
        qt = Q.front().t;
        for(int k = 0; k < 4; k++)
        {
            if(!A[qi + di[k]][qj + dj[k]])
            {
                Q.push({qi + di[k], qj + dj[k], qt});
                A[qi + di[k]][qj + dj[k]] = 1;
                sol += qt;
            }
        }
        Q.pop();
    }
    return;
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cin >> N >> M;
    for(int i = 1; i <= N; i++)
        for(int j = 1; j <= M; j++)
            cin >> C[i][j];

    for(int i = 1; i <= N; i++)
        for(int j = 1; j <= M; j++)
            if(C[i][j] == 'X') Q.push({i, j, 0});
    for(int i = 1; i <= N; i++)
        for(int j = 1; j <= M; j++)
            if(C[i][j] == 'S') Q.push({i, j, 1});
    for(int i = 1; i <= N; i++)
        for(int j = 1; j <= M; j++)
            if(C[i][j] == '*') A[i][j] = 1;

    for(int i = 1; i <= N; i++)
    {
        A[i][0] = 1;
        A[i][M + 1] = 1;
    }
    for(int i = 1; i <= M; i++)
    {
        A[0][i] = 1;
        A[N + 1][i] = 1;
    }
    BFS();
    printf("%d\n", sol);
    return 0;
}