#include <iostream>
#include <queue>
#include <vector>

using namespace std;

char lavirint[1000][1000];
int vatra[1000][1000];//kada vatra stize na neko polje
int steva[1000][1000]; //kada steva stize na neko polje

int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};

void bfs_vatra(queue<pair<int, int>>& poc_vatre, int n, int m)
{
    while (!poc_vatre.empty())
    {
        int x = poc_vatre.front().first;
        int y = poc_vatre.front().second;
        poc_vatre.pop();

        for (int i = 0; i < 4; i++)
        {
            int novi_x = x + dx[i];
            int novi_y = y + dy[i];
            if (novi_x >= 0 && novi_x < n && novi_y >= 0 && novi_y < m && lavirint[novi_x][novi_y] == '.' && vatra[novi_x][novi_y] == 0)
            {
                vatra[novi_x][novi_y] = vatra[x][y] + 1;
                poc_vatre.push({novi_x, novi_y});
            }
        }
    }
}

void bfs_steva(int poc_x, int poc_y, int n, int m)
{
    queue<pair<int, int>> kretanje;
    kretanje.push({poc_x, poc_y});
    steva[poc_x][poc_y] = 1;
    while (!kretanje.empty())
    {
        int x = kretanje.front().first;
        int y = kretanje.front().second;
        kretanje.pop();

        for (int i = 0; i < 4; i++)
        {
            int novi_x = x + dx[i];
            int novi_y = y + dy[i];
            if (novi_x >= 0 && novi_x < n && novi_y >= 0 && novi_y < m && lavirint[novi_x][novi_y] == '.' && steva[novi_x][novi_y] == 0)
            {
                if (vatra[novi_x][novi_y] == 0 || steva[x][y] + 1 < vatra[novi_x][novi_y])
                {
                    steva[novi_x][novi_y] = steva[x][y] + 1;
                    kretanje.push({novi_x, novi_y});
                }
            }
        }
    }
}

int main()
{
    int n, m;
    cin>>n >> m;

    queue<pair<int, int>> poc_vatre;
    int poc_x, poc_y;

    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            cin>>lavirint[i][j];
            vatra[i][j] = 0;//nije vatra
            steva[i][j] = 0;//nije steva

            if (lavirint[i][j] == 'X')
            {
                vatra[i][j] = 1;//jeste vatra
                poc_vatre.push({i, j});
            }
            if (lavirint[i][j] == 'S')
            {
                steva[i][j] = 1;//jeste steva
                poc_x = i;
                poc_y = j;
            }
        }
    }

    bfs_vatra(poc_vatre, n, m);
    bfs_steva(poc_x, poc_y, n, m);

    int r = 0;
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            if (lavirint[i][j] == '.' && steva[i][j] > 0 && (vatra[i][j] == 0 || steva[i][j] < vatra[i][j]))
            {
                r++;
            }
        }
    }

    cout << r+1;
    return 0;
}