#include<iostream>
#include<queue>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
const int N=60;
typedef pair<int,int> PII;
int n,m;
int g[N][N];
vector<PII> a,b;
queue<PII> q;
bool st[N][N];
int ans=1e9;
void bfs(int x,int y,int k){
PII temp={x,y};
q.push(temp);
if(!k){
a.push_back(temp);
}else{
b.push_back(temp);
}
st[x][y]=true;
while(!q.empty()){
auto t=q.front();
q.pop();
int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
for(int i=0;i<4;i++){
int nx=t.first+dx[i],ny=t.second+dy[i];
if(nx>=0 && nx<n && ny>=0 && ny<m && g[nx][ny]==1 && st[nx][ny]==false){
q.push({nx,ny});
if(!k){
a.push_back({nx,ny});
}else{
b.push_back({nx,ny});
}
st[nx][ny]=true;
}
}
}
}
int get(int x1,int y1,int x2,int y2){
return (abs(x1-x2) + abs(y1-y2));
}
int main(){
cin>>n>>m;
memset(st,false,sizeof(st));
int t=0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
char c;
cin>>c;
if(c=='X'){
g[i][j]=1;
}else{
g[i][j]=0;
}
}
}
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(g[i][j]==1 && !st[i][j]){
bfs(i,j,t);
t=1;
}
}
}
for(int i=0;i<a.size();i++){
for(int j=0;j<b.size();j++){
ans=min(ans,get(a[i].first,a[i].second,b[j].first,b[j].second));
}
}
cout<<ans-1<<endl;
return 0;
}