#include<bits/stdc++.h>
using namespace std;
int r,c;
int tot=0;
char ch[55][55];
bool used[55][55];
int dx[4]={0,0,1,-1},dy[4]={1,-1,0,0};
int g[55][55],begin[2505][2];
int visit[55][55];
void dfs(int x,int y)
{
visit[x][y]=tot;
for (int i=0;i<=3;i++){
int xx=x+dx[i],yy=y+dy[i];
if (xx>=1 && xx<=r && yy>=1 && yy<=c && visit[xx][yy]==0 && ch[xx][yy]=='X')
dfs(xx,yy);
}
}
struct mm{
int x,y,step;
mm(int a,int b,int c){
x=a;y=b;step=c;
}
};
void bfs(int x)
{
queue<mm> q;
q.push(mm(begin[x][0],begin[x][1],0));
while (!q.empty()){
mm head=q.front(); q.pop();
if (visit[head.x][head.y]!=x && ch[head.x][head.y]=='X' && g[x][visit[head.x][head.y]]==0)
g[visit[head.x][head.y]][x]=g[x][visit[head.x][head.y]]=head.step;
for (int i=0;i<=3;i++){
int xx=head.x+dx[i],yy=head.y+dy[i];
if (xx>=1 && xx<=r && yy>=1 && yy<=c && used[xx][yy]==0 && ch[xx][yy]!='.'){
used[xx][yy]=1;
int cost=0;
if (ch[head.x][head.y]=='X'){
if (ch[xx][yy]=='X') cost=0;
if (ch[xx][yy]=='S') cost=1;
}
if (ch[head.x][head.y]=='S'){
if (ch[xx][yy]=='S') cost=1;
if (ch[xx][yy]=='X') cost=0;
}
q.push(mm(xx,yy,head.step+cost));
}
}
}
}
int dp[1<<16][25];
int main()
{
cin>>r>>c;
for (int i=1;i<=r;i++){
for (int j=1;j<=c;j++){
cin>>ch[i][j];
}
}
for (int i=1;i<=r;i++)
for (int j=1;j<=c;j++){
if (visit[i][j]==0 && ch[i][j]=='X'){
tot++;
dfs(i,j);
begin[tot][0]=i;begin[tot][1]=j;
}
}
for (int i=1;i<=tot;i++){
memset(used,0,sizeof used);
bfs(i);
}
memset(dp,0x3f,sizeof dp);
dp[1][1]=0;
for (int i=0;i<(1<<tot);i++){
for (int now=1;now<=tot;now++){
if (!(i>>(now-1)&1)){
for (int pre=1;pre<=tot;pre++){
if (i>>(pre-1)&1){
dp[i|(1<<(now-1))][now]=min(dp[i|(1<<(now-1))][now],dp[i|(1<<(pre-1))][pre]+g[pre][now]);
}
}
}
}
}
cout<<dp[(1<<tot)-1][tot];
return 0;
}