#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <queue>
#define MAX_N 1000
#define MAX_M 1000

int n, m;
char l[MAX_N][MAX_M];
int v[MAX_N][MAX_M];
int s[MAX_N][MAX_M];
int d[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
void bfs_v()
{
    std::queue<std::pair<int, int>> q;
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            if (l[i][j] == 'X')
            {
                q.push({i, j});
                v[i][j] = 0;
            }
            else
                v[i][j] = -1;
        }
    }
    while (!q.empty())
    {
        int x = q.front().first;
        int y = q.front().second;
        q.pop();
        for (int i = 0; i < 4; i++)
        {
            int nx = x + d[i][0];
            int ny = y + d[i][1];
            if (nx >= 0 && nx < n && ny >= 0 && ny < m && (v[nx][ny] == -1 || v[nx][ny]>v[x][y] + 1) && l[nx][ny] != '*')
            {
                v[nx][ny] = v[x][y] + 1;
                q.push({nx, ny});
            }
        }
    }
}
void bfs_s(int sx, int sy)
{
    std::queue<std::pair<int, int>> q;
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            s[i][j] = -1;
        }
    }
    q.push({sx, sy});
    s[sx][sy] = 0;
    while (!q.empty())
    {
        int x = q.front().first;
        int y = q.front().second;
        q.pop();
        for (int i = 0; i < 4; i++)
        {
            int nx = x + d[i][0];
            int ny = y + d[i][1];
            if (nx >= 0 && nx < n && ny >= 0 && ny < m && s[nx][ny] == -1 && l[nx][ny] != '*' && (v[nx][ny] == -1 || s[x][y] + 1 < v[nx][ny]))
            {
                s[nx][ny] = s[x][y] + 1;
                q.push({nx, ny});
            }
        }
    }
}

int main()
{
    scanf("%d", &n);
    scanf("%d", &m);
    int sx, sy;
    for (int i = 0; i < n; i++)
    {
        scanf("%s", l[i]);
        for (int j = 0; j < m; j++)
        {
            if (l[i][j] == 'S')
            {
                sx = i;
                sy = j;
            }
        }
    }
    bfs_v();
    bfs_s(sx, sy);
    int br = 0;
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            if (s[i][j] != -1)
            {
                br++;
            }
        }
    }
    printf("%d\n", br);
    return 0;
}