#include <iostream>
#include <queue>
#include <string>

using namespace std;

typedef struct{
    int x,y;
} Polje;

int main()
{
    int n,m;
    cin>>n>>m;
    string mat[n];
    for (int i=0;i<n;i++){
        cin>>mat[i];
    }
    queue<Polje> steva;
    queue<Polje> vatra;
    char c;
    int brvatre=0;
    int brsteve=1;
    for (int i=0;i<n;i++)
    {
        for (int j=0;j<m;j++)
        {
            c=mat[i][j];
            if(c=='S'){
                Polje p={i,j};
                steva.push(p);
            }
            else if (c=='X')
            {
                Polje p={i,j};
                vatra.push(p);
                brvatre++;
            }
        }
    }
    int konacanbroj=1;
    while (brsteve)
    {
        int brv=brvatre;
        brvatre=0;
        if(brv){
            for (int i=0;i<brv;i++){
                Polje v=vatra.front();
                if(v.y>0 && mat[v.x][v.y-1]=='.'){
                    mat[v.x][v.y-1]='X';
                    Polje p={v.x,v.y-1};
                    vatra.push(p);
                    brvatre++;
                }
                if(v.y<m-1 && mat[v.x][v.y+1]=='.'){
                    mat[v.x][v.y+1]='X';
                    Polje p={v.x,v.y+1};
                    vatra.push(p);
                    brvatre++;
                }
                if(v.x>0 && mat[v.x-1][v.y]=='.'){
                    mat[v.x-1][v.y]='X';
                    Polje p={v.x-1,v.y};
                    vatra.push(p);
                    brvatre++;
                }
                if(v.x<n-1 && mat[v.x+1][v.y]=='.'){
                    mat[v.x+1][v.y]='X';
                    Polje p={v.x+1,v.y};
                    vatra.push(p);
                    brvatre++;
                }
                vatra.pop();
            }
        }
        int brs=brsteve;
        brsteve=0;
        for(int i=0;i<brs;i++)
        {
            Polje s=steva.front();
            if(s.y>0 && mat[s.x][s.y-1]=='.'){
                mat[s.x][s.y-1]='S';
                Polje p={s.x,s.y-1};
                steva.push(p);
                brsteve++;
            }
            if(s.y<m-1 && mat[s.x][s.y+1]=='.'){
                mat[s.x][s.y+1]='S';
                Polje p={s.x,s.y+1};
                steva.push(p);
                brsteve++;
            }
            if(s.x>0 && mat[s.x-1][s.y]=='.'){
                mat[s.x-1][s.y]='S';
                Polje p={s.x-1,s.y};
                steva.push(p);
                brsteve++;
            }
            if(s.x<n-1 && mat[s.x+1][s.y]=='.'){
                mat[s.x+1][s.y]='S';
                Polje p={s.x+1,s.y};
                steva.push(p);
                brsteve++;
            }
            steva.pop();
        }
        konacanbroj+=brsteve;
    }
    cout<<konacanbroj;
}