#include <bits/stdc++.h> 
using namespace std;

int main()
{
	string unos;
	int N,M;
	cin>>N>>M;
	string mtx[N][M];
	int j=0;
	string str;
	int brs=0;
	int brsp =0;
	int st1[N*M];
	int st2[N*M];
	int va1[N*M];
	int va2[N*M];
	int brv=0;
	int brvp =0;
	int doda=1;
	int br=0;
	for(int i =0;i<N;i++)
	{
		cin>>str;
        for(int o =0;o<M;o++)
		{
			mtx[i][o]=str.substr(o,1);
			if(mtx[i][o]=="X")
			{
				va1[brv]=i;
				va2[brv]=o;
				brv++;
			}
			if(mtx[i][o]=="S")
			{
				st1[brs]=i;
				st2[brs]=o;
				brs++;
			}
			//br++;
		}		
		brvp=brv;
		brsp=brs;
		
	}
    /*for(int i =0;i<N;i++)
	{
		for(int o =0;o<M;o++)
		{
			cout<<mtx[i][o]<<" ";
		}
		cout<<endl;
	}*/
		while(doda!=0)
	{
		doda=0;
		while(brv>0)
		{
			if(mtx[va1[brv]][va2[brv-1]]==".")
			{
				va1[brvp]=va1[brv];
				va2[brvp]=va2[brv-1];
				brvp++;
			}
			if(mtx[va1[brv]][va2[brv+1]]==".")
			{
				va1[brvp]=va1[brv];
				va2[brvp]=va2[brv+1];
				brvp++;
			}
			if(mtx[va1[brv-1]][va2[brv]]==".")
			{
			   va1[brvp]=va1[brv-1];
				va2[brvp]=va2[brv];
				brvp++;
			}
			if(mtx[va1[brv+1]][va2[brv]]==".")
			{
					va1[brvp]=va1[brv+1];
				va2[brvp]=va2[brv];
				brvp++;
			}
			brv--;
		}
		brv=brvp;
		while(brs>0)
		{
			if(mtx[st1[brs]][st2[brs-1]]==".")
			{
				mtx[st1[brs]][st2[brs-1]]=="S";
				doda++;
				st1[brsp]=st1[brs];
				st2[brvp]=st2[brs-1];
				brsp++;
				br++;
			}
			if(mtx[st1[brs]][st2[brs+1]]==".")
			{
					mtx[st1[brs]][st2[brs+1]]=="S";
				doda++;
				st1[brsp]=st1[brs];
				st2[brvp]=st2[brs+1];
				brsp++;
				br++;
			}
			if(mtx[st1[brs-1]][st2[brs]]==".")
			{
					mtx[st1[brs-1]][st2[brs]]=="S";
				doda++;
				st1[brsp]=st1[brs-1];
				st2[brvp]=st2[brs];
				brsp++;
				br++;
			}
			if(mtx[st1[brs+1]][st2[brs]]==".")
			{
					mtx[st1[brs+1]][st2[brs]]=="S";
				doda++;
				st1[brsp]=st1[brs+1];
				st2[brvp]=st2[brs];
				brsp++;
				br++;
			}
			brs--;
		}
		brs=brsp;
		
	}


	cout<<brs;
}