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

const int pomerajRed[] = { -1, 1, 0, 0 };
const int pomerajKolona[] = { 0, 0, -1, 1 };

bool validno(int red, int kolona, int n, int m) 
{
    return red >= 0 && red < n&& kolona >= 0 && kolona < m;
}

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

    vector<string> lavirint(n);
    for (int i = 0; i < n; i++) 
    {
        cin >> lavirint[i];
    }

    vector<vector<int>> vremeVatre(n, vector<int>(m, -1));
    vector<vector<int>> vremeSteve(n, vector<int>(m, -1));

    queue<pair<int, int>> redVatre, redSteve;

    int startRed = -1, startKolona = -1;

    for (int i = 0; i < n; i++) 
    {
        for (int j = 0; j < m; j++) 
        {
            if (lavirint[i][j] == 'X') 
            {
                redVatre.push({ i, j });
                vremeVatre[i][j] = 0;
            }
            if (lavirint[i][j] == 'S') 
            {
                startRed = i;
                startKolona = j;
                redSteve.push({ i, j });
                vremeSteve[i][j] = 0;
            }
        }
    }

    while (!redVatre.empty())
    {
        auto [trenutniRed, trenutnaKolona] = redVatre.front();
        redVatre.pop();

        for (int k = 0; k < 4; k++) 
        {
            int noviRed = trenutniRed + pomerajRed[k];
            int novaKolona = trenutnaKolona + pomerajKolona[k];

            if (validno(noviRed, novaKolona, n, m) && lavirint[noviRed][novaKolona] == '.' && vremeVatre[noviRed][novaKolona] == -1) 
            {
                vremeVatre[noviRed][novaKolona] = vremeVatre[trenutniRed][trenutnaKolona] + 1;
                redVatre.push({ noviRed, novaKolona });
            }
        }
    }

    int brojPolja = 0;
    while (!redSteve.empty()) 
    {
        auto [trenutniRed, trenutnaKolona] = redSteve.front();
        redSteve.pop();

        for (int k = 0; k < 4; k++) 
        {
            int noviRed = trenutniRed + pomerajRed[k];
            int novaKolona = trenutnaKolona + pomerajKolona[k];

            if (validno(noviRed, novaKolona, n, m) && lavirint[noviRed][novaKolona] == '.' && vremeSteve[noviRed][novaKolona] == -1) 
            {
                vremeSteve[noviRed][novaKolona] = vremeSteve[trenutniRed][trenutnaKolona] + 1;

                if (vremeVatre[noviRed][novaKolona] == -1 || vremeSteve[noviRed][novaKolona] < vremeVatre[noviRed][novaKolona]) 
                {
                    redSteve.push({ noviRed, novaKolona });
                    brojPolja++;
                }
            }
        }
    }

    cout << brojPolja + 1 << endl;
}