#include <iostream>
#include <vector>
using namespace std;
struct coord{
int i;
int j;
};
int main()
{
    int n,m;
    cin>>n>>m;
    char arr[n][m];
    int arrf[n][m];
    int arrs[n][m];
    vector<coord> fire;
    coord curs; coord curf; // ????? ? ???? ?? ?????
    vector<coord>steva;
        for(int i=0;i<n;i++){
        for(int j=0;j<m;j++){
            cin>>arr[i][j];
            if(arr[i][j]=='X'){
                curf.i=i;curf.j=j; fire.push_back(curf); arrf[i][j]=0;
            }
            else if(arr[i][j]=='S'){curs.i=i;curs.j=j;steva.push_back(curs);arrf[i][j]=0;}
            else if(arr[i][j]=='*')arrf[i][j]=-1;
            else arrf[i][j]=0;
        arrs[i][j]=arrf[i][j];
        }
    }

int ipis = 1; // ??????? ??????????????
vector<coord> firenew; //??????, ?? ??????? ??????????? ????? ????? ?????
while (fire.empty()!=true){
    for (int fi=0;fi<fire.size();fi++){
        coord curf=fire[fi];
        int i=curf.i;
        int j=curf.j;
        if (arrf[i][j] == 0 || arrf[i][j] > ipis)arrf[i][j]=ipis;
        if (i>0 && arrf[i-1][j]==0)firenew.push_back({i-1,j});
        if (i<n-1 && arrf[i+1][j]==0)firenew.push_back({i+1,j});
        if (j>0 && arrf[i][j-1]==0)firenew.push_back({i,j-1});
        if (j<m-1 && arrf[i][j+1]==0)firenew.push_back({i,j+1});
    }


    // ????? ???? ?????????????? ?
    fire = firenew;
    firenew.clear();
    ipis++;
}

fire.clear();
fire.push_back(curs); //????? ?? ???????? ??? ?????
ipis=1;
while (fire.empty()!=true){
    for (int fi=0;fi<fire.size();fi++){
        coord curf=fire[fi];
        int i=curf.i;
        int j=curf.j;
        if (arrs[i][j] == 0 || arrs[i][j] > ipis)arrs[i][j]=ipis;
        if (i>0 && arrs[i-1][j]==0)firenew.push_back({i-1,j});
        if (i<n-1 && arrs[i+1][j]==0)firenew.push_back({i+1,j});
        if (j>0 && arrs[i][j-1]==0)firenew.push_back({i,j-1});
        if (j<m-1 && arrs[i][j+1]==0)firenew.push_back({i,j+1});
    }


    // ????? ???? ?????????????? ?
    fire = firenew;
    firenew.clear();
    ipis++;
}

        int ans=0;
 for(int i=0;i<n;i++){
        for(int j=0;j<m;j++){
          if(arrs[i][j]<arrf[i][j] && arrs[i][j]!=0)ans++;
          else if(arrf[i][j]==0 && arrs[i][j]>0)ans++;
        }
    }
    cout<<ans;
    return 0;
}